0

使用 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

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

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

我在这里想念什么?

4

1 回答 1

0

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

complete(jqXHR, textStatus)

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

您可能想改用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);
    }
});
于 2012-08-12T21:12:54.307 回答