如何调试jQuery Ajax请求?

我的代码是:

var test = "it isn't working"; var response = $.ajax({ type: 'GET', url: 'jquerydemo.php', //This is in the same site as the page calling this request, so it's not a same-domain error. success: function(){ test = "it's working"; }, error: function(){ alert("Error detected"); } }).responseText; alert(test); 

我测试了状态代码,它出现了200并且错误函数永远不会消失,但成功函数也没有。 就像我在评论中所说的那样,它不是同源政策错误。 它只是说“它不起作用”。 这里发生了什么?

试试这个:

  error: function(jqXHR, textStatus, errorThrown) { console.log(JSON.stringify(jqXHR)); console.log("AJAX error: " + textStatus + ' : ' + errorThrown); } 

你的ajax调用是异步的。 当你的警报结束时,它还没有完成。 在成功函数中添加实际警报,您应该在那里看到您的结果。

请记住,进行ajax调用只会启动异步ajax调用,然后其余代码继续运行。 在您发布的代码示例中,这意味着您的alert(test)调用在ajax调用完成之前立即运行。

您只能在成功处理程序本身内检查ajax调用的结果。

 var test = "it isn't working"; var response = $.ajax({ type: 'GET', url: 'jquerydemo.php', //This is in the same site as the page calling this request, so it's not a same-domain error. success: function(){ alert("it's working"); // put this here and you will see it // if the ajax call is successful }, error: function(){ alert("Error detected"); } }).responseText; 

为了调试这些类型的东西,我发现Firebug是一个不可或缺的工具。 它会准确显示服务器的响应(500错误,553错误,你有什么)。 您可以在Javascript代码中添加断点并逐步调试它。 Firebug适用于Firefox。

对于IE,您可以使用与Firebug类似的开发人员工具function,特别是在IE9上,这似乎比以前版本的IE7或IE8的开发人员工具更成熟。

将该警报(测试)从结束移动到ajax调用的成功函数。 如果它警告它意味着代码正在工作,否则它不是。 你只能在成功返回时调试ajax调用。

 var test = "it isn't working"; var response = $.ajax({ type: 'GET', url: 'jquerydemo.php', success: function(){ test = "it's working"; alert(test); //It will alert when you ajax call returns successfully. }, error: function(){ alert("Error detected"); } }).responseText; 

希望这可以帮助。

你可以做到这一点

  var response = $.ajax({ type: 'GET', url: 'jquerydemo.php', success: function(){ alert("it's working"); }, error: function(){ alert("Error detected"); } }).responseText; 

这将工作….