Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

366
Vistas
Envío de datos entre Flask y JS usando AJAX para la extensión de Chrome

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 data

Error

 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 !

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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'])
over 4 years ago · Santiago Trujillo Denunciar

0

$(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); });
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda