究竟是什么触发了jQuery ajax的成功?

kev*_*ler 6 jquery dancer

我在Perl Web框架中构建一些ajax Dancer我不确定它是否正在响应正确的http头,因为我无法从看似成功的请求中触发jQuery的ajax成功处理程序.使用下面的ajax片段,我在浏览器控制台中获得以下输出.完整的回调被成功调用,并提供看起来成功的输出.Status:200 StatusText:"OK"然而,成功处理程序永远不会被调用.

$.ajax({type: "GET", url: "/learn/faq",
 success: function(data){console.log('omg got it');},
 complete: function(data){console.log("complete", data);}
}).success(function(data){console.log('defered');});


Object
XHR finished loading: "https://www.localhost:4443/learn/faq". assets-d36e1bb9fd59ba3dbd0f8a0cbb37ed8e.js:1
complete 
Object {readyState: 4, responseText: "??<!DOCTYPE html>?<html xmlns="http://www.w3.org/1…ead/conversion.js"></script>????</body>?</html>??", status: 200, statusText: "OK"
Run Code Online (Sandbox Code Playgroud)

我应该看到omg got itdefered消息,但不是.看看这个我觉得jQuery成功处理程序比状态和Dancer http实现没有正确响应更多.

此外,我已经error在片段中添加了一个处理程序,并且错误处理程序正在被看似成功的请求触发.

$.ajax({type: "GET", url: "/learn/faq",
 success: function(data){console.log('omg got it');},
 complete: function(data){console.log("complete", data);},
error: function(data){console.log("error!", data);}
}).success(function(data){console.log('defered');});
Object
XHR finished loading: "https://www.localhost:4443/learn/faq". assets-8cd028b93e0db9dd9455125dc98d5ae1.js:1
error! 
Object {readyState: 4, responseText: "????????????????<!DOCTYPE html>?<html xmlns="http:…></script>????</body>?</html>????</body>?</html>?", status: 200, statusText: "OK"}
complete 
Object {readyState: 4, responseText: "????????????????<!DOCTYPE html>?<html xmlns="http:…></script>????</body>?</html>????</body>?</html>?", status: 200, statusText: "OK"}
Run Code Online (Sandbox Code Playgroud)

以下是来自的响应标头 jQuery getAllResponseHeaders()

complete Date: Tue, 01 Jan 2013 22:43:52 GMT
Content-Encoding: gzip
X-Powered-By: Perl Dancer 1.3095.1
Transfer-Encoding: chunked
Connection: keep-alive
Server: nginx/1.2.4
Strict-Transport-Security: max-age=2592000
Content-Type: text/xml; charset=utf-8
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 12

success处理器将被触发,如果

  • 响应有HTTP状态代码200(你的)
  • jQuery能够根据响应中的Content-Type标头反序列化响应(或者dataType,如果提供它,则选项会覆盖Content-Type标头)

因此,例如,如果您的响应的Content-Type标头为application/jsonapplication/xml,则您引用的响应将不会触发success处理程序,因为它无法成功反序列化为JSON或XML.


您的最新编辑(截至撰写本文时)揭示了问题:

以下是jQuery getAllResponseHeaders()的响应头

...

Content-Type: text/xml; charset=utf-8

我怀疑你的响应不是有效的XML,所以jQuery不能将它反序列化为XML,所以它失败了.