为什么我的JSONP返回无效的JSON

1 投票
2 回答
3922 浏览
提问于 2025-04-17 02:23

我现在正在用Python/Django从一个外部的XML文件中提取数据,并把它转换成JSON格式。遇到的问题是,当我在JQUERY中获取这个JSON时,出现了“无效的JSON”的错误。不过,当我把我的JSON放到像JSONFormatter这样的验证工具中检查时,它却告诉我我的JSON是有效的。

这是我的Python代码:

def test(request):


    tree = lxml.etree.parse("http://somedomain.com")
    deals = tree.xpath("/page/deals/deal")

    deals_info = []

    for deal in deals:
        this_value = {
            "id":deal.find("id").text,
            "totaldealcount":deal.find("totaldealcount").text,
            "offer":deal.find("offer").text,
            "link":deal.find("link").text,
            "merchantname":deal.find("merchantname").text,
            "saleprice":deal.find("saleprice").text,
            "productvalue":deal.find("productvalue").text,
            }
        deals_info.append(this_value)


    json_deals = '{"deals":' + simplejson.dumps(deals_info) + '}'

    if("callback" in request.GET.keys()):
        callback = request.GET["callback"]
    else:
        callback = None

    if(callback):
        response = HttpResponse("%s(%s)" % (
                callback,
                simplejson.dumps(deals_info)
                ), mimetype="application/json"
            )
    else:
        response = HttpResponse(json_deals, mimetype="application/json")
    return response

这是返回的JSON:

    mycallback([{"productvalue": "40.00", "totaldealcount": "4", "merchantname": "Joes Door Knobs", "offer": "$40 Deal for $20", "link": "http://somelink.com", "saleprice": "20.00", "id": "3112264"}, {"productvalue": "20.00", "totaldealcount": "4", "merchantname": "Bob's Pizza", "offer": "$20 Deal for $10", "link": "http://somelink.com", "saleprice": "10.00", "id": "3112266"}])

这是我的jQuery代码:

$.ajax({
    url: "http://www.urltomydomain.com?callback=mycallback",
    data: {},
    dataType: "json",
    success: function(json) {
    console.log('success');
    console.log(json);
    },
    error: function(x,y,z) {
    // x.responseText should have what's wrong
        console.log(x)
        console.log(y)
        console.log(z)
    }
});

任何帮助都会很感激。

谢谢

2 个回答

0

JSONP的主要目的就是你不是在返回JSON数据,而是返回浏览器可以执行的JavaScript代码

与其使用jQuery的AJAX功能(而且还错误地告诉它期待返回的类型是json),你可以直接在页面上添加一个新的<script>标签:

$.getScript('http://www.urltomydomain.com?callback=mycallback');
4

你需要告诉 jQuery 这是 JSONP(其实就是一种脚本,它是一个带有你 JSON 数据的函数调用),而不是普通的 JSON 数据。它会提示“无效的 JSON”,是因为 jQuery 正在尝试解析这个函数调用。

$.ajax({
    url: "http://www.urltomydomain.com",
    dataType: "jsonp",
    success: function(json) {
        console.log('success');
        console.log(json);
    },
    error: function(x,y,z) {
        // x.responseText should have what's wrong
        console.log(x)
        console.log(y)
        console.log(z)
    }
});

dataType: "jsonp" 会自动在你的网址后面加上 ?callback=?,所以这里不需要再加了。

你也可以使用 getJSON(这需要你手动加上 ?callback=?)。

$.getJSON('http://www.urltomydomain.com?callback=?', function(json){
    console.log('success');
    console.log(json);
});

你应该使用 ?callback=?,因为 jQuery 会自动把第二个 ? 替换成一个动态生成的回调函数名称。

撰写回答