【问题标题】:jQuery won't handle application/json response correctlyjQuery 不会正确处理应用程序/json 响应
【发布时间】:2012-08-12 18:01:16
【问题描述】:

使用 jQuery 1.8 和 Kohana 进行简单的 jQuery ajax 调用和响应:

$.ajax({
    data:{
        file: file  
},
    dataType: 'json',
    url: 'media/delete',
    contentType: 'application/json; charset=utf-8',
    type: 'GET',
    complete: function(response){
        console.log(response);
        console.log(response.file);
    }
});

URL 的 PHP 是一个简单的 json_encode() 页面,返回:

{"file":"uploaded\/img\/Screen Shot 2012-04-21 at 2.17.06 PM-610.png"}

根据 JSLint,哪个是有效的 JSON。

根据萤火虫的说法,响应标头是:

Response Headers
Connection  Keep-Alive
Content-Length  74
Content-Type    application/json
Date    Sun, 12 Aug 2012 17:44:39 GMT
Keep-Alive  timeout=5, max=97
Server  Apache/2.4.1 (Unix) PHP/5.4.0
X-Powered-By    PHP/5.4.0

但是在成功函数中“response”不是我期望的JS对象,我无法访问response.file。相反,它似乎是某种响应对象,包含 readyState、responseText、状态等字段。

这里有很多类似的问题,但我相信我已经根据其他答案正确连接了所有内容。

我在这里错过了什么?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    complete: 回调不提供响应作为它的参数。来自jQuery doc for $.ajax()

    complete(jqXHR, textStatus)
    

    因此,您所看到的完整函数的参数是 jqXHR 对象,而不是解析后的响应。这可能是因为无论成功与否,在完成 ajax 调用时都会调用 complete。获取成功解析的 JSON 响应的是 success 处理程序。

    您可能想改用success: 回调。

    $.ajax({
        data: {file: file},
        dataType: 'json',
        url: 'media/delete',
        contentType: 'application/json; charset=utf-8',
        type: 'GET',
        success: function(response){
            console.log(response);
            console.log(response.file);
        }
    });
    

    【讨论】:

    • 哦,哇,我想这是很明显的东西,我只是看不到,谢谢。
    猜你喜欢
    • 2013-07-16
    • 2012-01-29
    • 1970-01-01
    • 2018-05-20
    • 2012-05-15
    • 2019-04-29
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多