【问题标题】:Exception handling in AjaxAjax 中的异常处理
【发布时间】:2014-03-02 22:50:01
【问题描述】:

我正在从我的 HTTPS 页面进行以下 ajax 调用,

 $.ajax({
    url: "http://www.w3schools.com",
    dataType: 'jsonp',
    crossDomain: true,
    complete: function (e, xhr, settings) {
        switch (e.status) {
            case 200:
                //everything fine
                break;
            default: 
                //Somethings wrong, show error msg                                   
                break;
        }
    }
});

但由于我是从 HTTPS 页面进行 HTTP 调用,所以调用被阻止。 我可以在控制台(CHROME)中看到“不安全的内容警告”,

但是在完成、错误或成功中都没有捕获到错误。他们根本不开火。

我需要捕捉错误。 有什么办法可以做到这一点?

【问题讨论】:

标签: jquery ajax https


【解决方案1】:
 error
    Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )

A function to be called if the request fails. The function receives three arguments: The 

jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that 

occurred and an optional exception object, if one occurred. Possible values for the second 

argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP 

error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not 

Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array 

of functions. Each function will be called in turn. Note: This handler is not called for 

cross-domain script and cross-domain JSONP requests. This is an [Ajax Event][1].

试试这个,

使用jqXHR.status查找请求状态

Demo

$.ajax({
    url: "http://www.w3schools.com",
    dataType: 'jsonp',
    crossDomain: true,
    complete: function (e, xhr, settings) {
        switch (e.status) {
            case 200:
                //everything fine
                break;
            default: 
                //Somethings wrong, show error msg                                   
                break;
        }
    },
    error: function(jqXHR, textStatus, errorThrown){

    alert(errorThrown)
    },
});

【讨论】:

  • 是的,这显示了小提琴中的警报,因为它是一个 HTTP 站点。但在 HTTPS 站点中尝试此操作不会触发错误 :(
  • @Targarian 我更新了我的答案,如果有用请接受我的答案。因为下一个用户遵循这个答案。谢谢
  • 是的,但是我们仍然没有办法找到这种不安全的内容请求吗?
  • 是的,您可以使用textStatus 找到。 stackoverflow.com/questions/19262520/…
  • 是的,但我需要触发错误事件才能找到 textStatus。这就是问题所在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-31
  • 2011-12-26
  • 2020-06-26
相关资源
最近更新 更多