【问题标题】:Jquery ajax response says "Unexpected token ':'" (using jsonp as datatype) [duplicate]Jquery ajax响应说“意外的令牌':'”(使用jsonp作为数据类型)[重复]
【发布时间】:2018-07-16 07:11:43
【问题描述】:

我有一个用PythonFlask 编写的演示网络服务器,我正在使用jsonp 通过jquery 对该服务器进行ajax 调用。 url 返回 json 作为响应,但脚本无法将其解析为 json。 错误提示 Unexpected token ":". 下面是 webserver 和 ajax 调用的代码,我还注释了出现错误的行。

from flask import Flask, jsonify, render_template
    app = Flask(__name__)


@app.route("/")
def index():
    html = (
        """<button type="button" id="button_1">Click Me !</button>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script type="text/javascript">
            $('#button_1').click(function() {
                var url = 'http://127.0.0.1:5000/url';
                alert(url);
                $.ajax({
                     url: url,
                     type: 'GET',
                     dataType: 'jsonp',
                     jsonpCallback: 'processJSONPResponse',
                     contentType: "application/json; charset=utf-8",
                     complete: function(data, status, jqXHR) {
                         console.log(data);
                     },
                     error: function(xhr, ajaxOptions, thrownError) {
                         console.log(xhr.responseText);
                     }
                });
            });
        </script>"""
    )
    return html


@app.route("/url")
def get_urls():
    response = {
        "urls": { # for the ajax call, I get an error as Unexpected token ":".
            "url1": "/api/repos/url1", 
            "url2": "/api/repos/url2", 
            "url3": "/api/repos/url3"
        }
    }
    return jsonify(response)


if __name__ == "__main__":
    app.run(debug=True)

我对 javascript (jquery) 很陌生,无法找出问题所在。任何帮助将不胜感激。

【问题讨论】:

  • 该 ajax 调用得到的响应是什么?

标签: jquery python ajax flask


【解决方案1】:

您确定需要 JSONP,而不仅仅是 JSON?

当您不允许使用 XHR(由于同源策略,例如当您向其他域名发出请求并且它不提供 CORS 标头时)时,JSONP 用于加载 JSON 数据,并提供基于注入的解决方法&lt;script&gt; 标签。

如果您只需要 JSON,请将您的 dataType: 'jsonp' 更改为 dataType: 'json'

对于 JSONP,您的服务器应返回的不是 JSON 字符串,而是包含以 JSON 作为参数的函数调用的 JavaScript:

processJSONPResponse({
    "url1": "/api/repos/url1", 
    "url2": "/api/repos/url2", 
    "url3": "/api/repos/url3"
})

这个脚本将被 jQuery 作为&lt;script&gt; 标签插入,一旦插入,processJSONPResponse() 函数将与您的数据一起执行。由于您在发起 JSONP 请求时定义了回调名称 (jsonpCallback: 'processJSONPResponse'),因此 jQuery 将为您创建此回调函数,一旦评估了 &lt;script&gt;,将使用您的数据调用 complete 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-28
    • 2014-02-19
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 2014-12-16
    相关资源
    最近更新 更多