繁体   English   中英

如何调试jQuery Ajax请求?

[英]How do I debug a jQuery Ajax request?

我的代码是:

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类似的开发人员工具功能,特别是在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;

这将工作....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM