gpt4 book ai didi

javascript - 使用 AJAX 在 Flask 和 JS 之间发送数据以进行 chrome 扩展

转载 作者:行者123 更新时间:2023-12-03 17:09:53 25 4
gpt4 key购买 nike

我正在尝试使用 AJAX 调用在我的 chrome 扩展的 Javascript 前端和我计划使用机器学习代码的 Flask API 之间来回发送数据。
内容.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);
flask 代码
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 的新手。任何帮助都会非常有帮助。非常感谢 !

最佳答案

$(document).ready$.ajax需要 jQueryfetchwindow.addEventListener适用于几乎所有最新的浏览器$(document).ready => window.addEventListener('DOMContentLoaded', function(evt) {})$.ajax => fetch 注:调用$(document).ready每条推文的一次又一次循环内部不是一个好的选择,它会一次又一次地运行一堆代码而不是setIntervaldocument 之后可以调用一次加载完成。
内容.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);
});

关于javascript - 使用 AJAX 在 Flask 和 JS 之间发送数据以进行 chrome 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65326934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com