简体   繁体   English

从 Flask for jQuery 返回 jsonp 格式的响应

[英]Return a response in jsonp format from Flask for jQuery

I am very new to web development back-end and my goal is to call a python script from Javascript.我对 Web 开发后端非常陌生,我的目标是从 Javascript 调用 python 脚本。

Using Flask, I think I am able to host my python script on localhost port 5000 python code:使用 Flask,我想我可以在 localhost 端口 5000 python 代码上托管我的 python 脚本:

from flask import Flask

app = Flask(__name__)

@app.route('/sub', methods=['GET', 'POST'])
def my_func():
   """
   I want this function to be called using javascript 
   """

This is how I am trying to use ajax in JavaScript to call the function这就是我尝试在 JavaScript 中使用 ajax 来调用函数的方式

function logResults(json){
    console.log(json);
}    

$.ajax({
       url: "http://0.0.0.0:5000/sub",
       dataType: "jsonp",
       jsonpCallback: "logResults"
    });

I learned that you have to use jsonp in order to have a cross domain request.我了解到您必须使用 jsonp 才能进行跨域请求。 (for example I need to reach port 5000 on localhost while the javascript is running on port 9000 of localhost) (例如,当 javascript 在 localhost 的端口 9000 上运行时,我需要到达 localhost 上的端口 5000)

When trying to run this code, I am receiving尝试运行此代码时,我收到

Loading failed for the < script > with source “http://0.0.0.0:5000/sub?callback=logResults&_=1604937695311”. <script> 加载失败,源为“http://0.0.0.0:5000/sub?callback=logResults&_=1604937695311”。

Does anyone know where I could be making a mistake?有谁知道我在哪里可能会犯错误? Am I on the right track?我在正确的轨道上吗?

This worked for me, but does anyone know how to send a data parameter when dataType is jsonp?这对我有用,但是有谁知道当 dataType 是 jsonp 时如何发送数据参数?

$.ajax({
    url: "http://localhost:5000/sub",
    dataType: "jsonp",
    jsonpCallback: "logResults"
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM