Estoy tratando de usar llamadas AJAX para enviar datos de ida y vuelta entre mi interfaz de Javascript para mi extensión de Chrome y la API de Flask donde planeo usar mi código de aprendizaje automático.
contenido.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);código matraz
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 dataError
Uncaught ReferenceError: $ is not defined content.js:11 (anonymous function) // which points to line - $(document).ready(function () {Soy nuevo tanto en Javascript como en Flask. Cualquier ayuda sería realmente útil. Muchas gracias !
En primer lugar, no tiene instalado jQuery, por lo que no puede acceder a $ y su error
Error de referencia no capturado: $ no está definido
está diciendo eso. debe incluir jQuery en su código js para usar $ y llamar a ajax. simplemente siga el comentario de @scrappedcola y siga las instrucciones allí para agregar el script jQuery.
segundo, debe definir el punto final como POST .
@app.route('/_api_call', methods=['POST'])$(document).ready y $.ajax requiere jQuery
fetch y window.addEventListener funciona en casi todos los navegadores más recientes
$(document).ready => window.addEventListener('DOMContentLoaded', function(evt) {})
$.ajax => fetch
Nota: Llamar a $(document).ready una y otra vez dentro del bucle para cada tweet no es una buena opción, ejecutará un montón de código una y otra vez, en lugar de eso, se puede llamar a setInterval una vez que se complete la carga del document .
contenido.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); });