jquery ajax错误函数未正确执行

时间:2014-06-07 03:33:37

标签: javascript jquery ajax json

我正在使用JSON加载外部$.ajax()文件,我很困惑为什么我的错误函数只执行console.log或警报,但没有别的?在我的示例中,如果找到JSON,则屏幕变为蓝色。如果找不到JSON(即我将test.js文件的名称更改为不存在的内容),屏幕应该变为红色,但这不会发生。我的代码出了什么问题?

$.ajax({
        url: 'test.js',
        dataType: 'json',
        timeout: 3000,
        success: function( data ) { success() },
        error: function( data ) { fail() }
      });



function success(){
    $("body").css("background", "blue");  //this works!
    console.log("success");               //this works!
}


function fail(){
    $("body").css("background", "red");   //this doesn't work :(
    console.log("fail");                  //this works!
}

谢谢,

1 个答案:

答案 0 :(得分:1)

如果你在纯js中编写上述内容,你需要指定几乎相同的参数,刚才你明确知道发生了什么以及它为什么或不起作用,因为你可以检查所有内容并且它不会被jQuery方法。注意:交换机结构是我个人的偏好,大多数人都使用(readyState === 4 && status === 200),但我总是希望能够将其扩展为更复杂的错误处理。

var xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.timeout = 3000;
xhr.open("GET","test.js"); //method, url, async [default:true], username, password
xhr.onreadystatechange = function(){
    if(xhr.readyState === xhr.DONE){  
        switch(xhr.status){
           case:200  
               success(xhr); 
               break;
           default:
               failure(xhr);
               break;
        }
    }
}
xhr.send();

function success(request){
    document.body.style.background = "blue";
    console.log(request.status,request.statusText); //> 200 "OK"
}
function failure(request){
    document.body.style.background = "red";
    console.log(request.status,request.statusText); // reason for error
}

因为它不是一个jQuery的答案因此完全偏离主题我知道我会得到大量的downvotes,但我很好。我只需要回答其他一些问题来弥补代理人损失。