使用 jquery ajax 请求尝试/捕获

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2810128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:18:44  来源:igfitidea点击:

Try/Catch with jquery ajax request

jqueryajaxexception-handling

提问by Anthony

I am trying to build a Google Chrome extension that makes an ajax request. Something similar to the GMail Checker extension. The problem is that when I do the request using jquery, and I put in the wrong username/password, it fails silently, with the error callback function ignored.

我正在尝试构建一个发出 ajax 请求的 Google Chrome 扩展程序。类似于 GMail Checker 扩展的东西。问题是当我使用 jquery 执行请求时,我输入了错误的用户名/密码,它会静默失败,错误回调函数被忽略。

If I move the ajax call out of the background.html script (where I can't see the requests in the developer window), to the options.html script, I get a dialog box to re-authenticate. If I hit cancel, THEN the jquery error callback fires.

如果我将 ajax 调用从 background.html 脚本(在开发人员窗口中看不到请求)移到 options.html 脚本,我会收到一个对话框来重新进行身份验证。如果我点击取消,则 jquery 错误回调会触发。

But in the original model extension (again, the Gmail checker), they use plain (non-jquery) ajax calls with a try/catch, and if I put in the wrong credentials, I get an alert saying as much.

但是在原始模型扩展(再次是 Gmail 检查器)中,他们使用带有 try/catch 的普通(非 jquery)ajax 调用,如果我输入了错误的凭据,我会收到一条警告,说明同样多。

I tried wrapping the entire jquery call in a try/catch, like so:

我尝试将整个 jquery 调用包装在 try/catch 中,如下所示:

try {
    $.ajax({
        type: "POST",
        url: someurl,
        contentType : "text/xml",
        data: somedata,
        username: user,
        password: pass,
        success: function(data,status,xhr){
            alert("Hurrah!");
        },
        error: function(xhr, status, error){
            alert("Error!" + xhr.status);
        },
        dataType: "xml"
    });
} catch(e) {
    alert("You messed something up!");
}

But still nothing.

但还是什么都没有。

Is the error due to it being asynchronous, or is Chrome not returning the request as an error since it wants to re-prompt for credentials? Or do I just not know how to use try/catch?

错误是因为它是异步的,还是 Chrome 没有将请求作为错误返回,因为它想重新提示输入凭据?还是我只是不知道如何使用 try/catch?

Update

更新

Here is a very slimmed down version of how the model code does the request:

这是模型代码如何执行请求的非常精简的版本:

var req = new XMLHttpRequest();
req.onreadystatechange = function() {
    try {
        if ( req.readyState == 4 ) {
            //Do some stuff with results
        }
    }
    catch (ex) {
        alert('Error parsing response.');
    }
}
try {
    req.send (data);
}
catch (ex) {
    alert ('Something went wrong with the request.');
}

采纳答案by NeoNexus DeMortis

Try something more like this, where you have a function that runs on every request once completed, regardless of what happens. This should solve the problem:

尝试更像这样的事情,你有一个函数,一旦完成,就会在每个请求上运行,不管发生什么。这应该可以解决问题:

// Store a global var so we can all play nicely.

// Make sure this gets reset to false right before your AJAX call,
// or it will only work once!
var weHaveSuccess = false;

$.ajax({
    type: "POST",
    url: someurl,
    contentType : "text/xml",
    data: somedata,
    username: user,
    password: pass,
    success: function(data,status,xhr){
        alert("Hurrah!");
        weHaveSuccess = true;
    },
    error: function(xhr, status, error){
        alert("Error!" + xhr.status);
    },
    complete: function(){
        if(!weHaveSuccess){
             alert('Your username/password seems to be incorrect!');
        }
    },
    dataType: "xml"
});

回答by Stig Husby

The ajax error callback function do not throw an exception by itself. If you want to have a try/catch you should probably throwan exception yourself inside your error function. This will trigger your surrounding catch.

ajax 错误回调函数本身不会抛出异常。如果您想要尝试/捕获,您可能应该自己在错误函数中抛出异常。这将触发您周围的捕获。

PS! Sometimes you need to set the async:false parameter in the ajax call when you need to evaluate the result because by default the code will continue after the ajax request is initiated and asynchronously call the success or error callback at a later stage and only call that code.

附注!有时你需要在ajax调用中设置async:false参数,当你需要评估结果时,因为默认情况下,代码会在ajax请求发起后继续,并在稍后阶段异步调用成功或错误回调,只调用那个代码。