使用用于chrome扩展的AJAX在Flask和JS之间发送数据

2024-10-01 17:27:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用AJAX调用在chrome扩展的Javascript前端和我计划使用机器学习代码的FlaskAPI之间来回发送数据

content.js

console.log("Application GO");

function colorChanger() {
  let tweets = document.querySelectorAll("article");
  tweets.forEach(function (tweet) {
    $(document).ready(function () {
    $.ajax({
          type: "POST",
          contentType: "application/json;charset=utf-8",
          url: "/_api_call",
          traditional: "true",
          data: JSON.stringify({tweet}),
          dataType: "json"
          });
  });

    tweet.setAttribute("style", "background-color: red;");
  });
}

let timer = setInterval(colorChanger, 2000);

烧瓶代码

from flask import Flask, flash, request, redirect, url_for
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/_api_call', methods=['GET'])
def fake_news_detector():
    data = request.get_json()
    with open('temp.txt', 'w') as f:
        f.write(data)
    return data

错误

Uncaught ReferenceError: $ is not defined
content.js:11 (anonymous function) // which points to line -  $(document).ready(function () {

我对Javascript和Flask都是新手。任何帮助都会很有帮助。非常感谢


Tags: 代码jsonappflaskdatajsfunctioncontent
2条回答

$(document).ready$.ajax需要jQuery

fetchwindow.addEventListener在几乎所有最新的浏览器中都能工作

$(document).ready=>window.addEventListener('DOMContentLoaded', function(evt) {})

$.ajax=>fetch

注意:在每个tweet的内部循环中反复调用$(document).ready不是一个好的选择,它会反复运行一系列代码,而setInterval可以在document加载完成后调用一次

content.js

async function Request(url = '', data = {}, method = 'POST') {
  // Default options are marked with *
  const response = await fetch(url, {
    method: method, // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': "application/json;charset=utf-8",
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

console.log("Application GO");

function colorChanger() {
  let tweets = document.querySelectorAll("article");

  tweets.forEach(function (tweet) {
    let response = Request("/_api_call", {tweet});
    tweet.setAttribute("style", "background-color: red;");
  });
}

window.addEventListener('DOMContentLoaded', (event) => {
    console.log('Called once after document load');
    let timer = setInterval(colorChanger, 2000);
});

首先,您没有安装jQuery,因此无法访问$和您的错误

Uncaught ReferenceError: $ is not defined

他是这么说的。您应该在js代码中包含jQuery,以便使用$和调用ajax。只需按照@scrappedcola注释并按照那里的说明添加jQuery脚本

其次,需要将端点定义为POST

@app.route('/_api_call', methods=['POST'])

相关问题 更多 >

    热门问题