2

我尝试从我的 Web 服务器获取 JSON 数据,但它不起作用。

$.mobile.showPageLoadingMsg();
//$.getJSON('http://localhost:8000/'+site+'/?format=json&callback=?', {}, function(){alert();});

$.ajax({
    url : 'http://localhost:8000/'+site +'/?format=json&callback=?',
    type : 'GET',
    dataType : 'jsonp',
    jsonp : 'callback',
    success : function(){alert('success');},
    error : function(){alert('fail')}
});

$.getJSON$.ajax两个方法的回调函数根本没有触发。有什么问题?

我的网络服务器的代码:

response_data.append({
            'user_nickname' : post.user_nickname,
            'title' : post.title,
            'recommend' : post.recommend,
            'oppose' : post.oppose,
            'date' : str(post.date),
            'hit' : post.hit,
            'commentcount' : post.commentcount
            })
    return HttpResponse(simplejson.dumps(response_data), mimetype='application/json')

在检查器中,它返回get,200,ok,所以HttpResponse没有问题。

这是回应:

[{“命中”:5,“标题”:“ \uc624\ud1a0\uc774\uc2a4\ucf00\uc774\ud551 \ub418\ub294\uac00”,“评论数”:0,“反对”:0,“推荐” : 0, "日期": "2012-07-24 07:01:22.453000+00:00", "用户昵称": "\ud55c\uae00\ub85c\uc5​​bc\ub9c8\ub098\uae38\uac8c\uae4c\uc9c0\ uac00\ub2a5\ud558\ub7ef\uc778\u3131\u3147\u3139\u3147\ub05d"}, {"hit": 4, "title": "\uc5ec\uae30 \uae00\uc4f0\uba74?", "commentcount" :1,“反对”:0,“推荐”:0,“日期”:“2012-07-24 06:52:05.125000+00:00”,“用户昵称”:“\ud55c\uae00\ub85c\uc5​​bc\ ub9c8\ub098\uae38\uac8c\uae4c\uc9c0\uac00\ub2a5\ud558\ub7ef\uc778\u3131\u3147\u3139\u3147\ub05d"}]

$.ajax()从不触发成功回调函数。它只是调用错误alert('fail');

4

1 回答 1

2

您的响应不是 JSONP:它只是一个 JSON 数组。

如果您将呼叫中的 更改datatypeajax'json'那么您的回调应该会触发。

但是如果你真的需要使用 JSONP——如果你试图进行跨站点通信——那么你需要返回有效的 JSONP 作为你的服务器响应。您的服务器需要使用 javascript 函数调用形式的字符串进行响应,使用jsonp参数的值作为函数名称,并将 JSON 响应作为函数参数。

于 2012-07-28T09:32:32.687 回答