【问题标题】:$.ajax error function is not working$.ajax 错误函数不起作用
【发布时间】:2013-09-30 14:20:47
【问题描述】:

我正在处理一些现有的代码。我有以下代码:

$.ajax({
        type: "get",
        url: url ,
        dataType: "jsonp",
        cache: "false",
        jsonpCallback: "onJSONPLoad",
        success: function(json){
               alert('hi!');
               //perform operation
        },
        error: function() {
          alert('Error occurs!');
       }
});

现在当我传递有效的url 时,它工作正常。但是当我传递无效的url 时,它应该通过错误警报。但是脚本没有抛出任何错误警报。基本上我想验证url 参数还是失败了?请帮助我找出我的代码中的错误或建议我其他方法来实现。我检查了以下链接,但无法解决我的问题:

jQuery Ajax error handling, show custom exception messages
jQuery ajax error function, Ajax Success and Error function failure

更新: 我添加了以下代码来记录 jquery 控制台日志。

  @Override
            public boolean onConsoleMessage(ConsoleMessage cm) {
                Log.d("web chrome client", cm.message() + " -- From line "
                + cm.lineNumber() + " of "
                + cm.sourceId() );
                return true;
            }

发现以下错误: XMLHttpRequest cannot load file:///android_asset/xxxx/new_source.json?callback=onJSONPLoad. Origin null is not allowed by Access-Control-Allow-Origin. -- From line 1 of null

添加如下代码,app运行成功。

if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
  webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
}

所以,基本上这是因为 url 无法被 jquery 访问。
感谢大家帮助我。

【问题讨论】:

标签: jquery


【解决方案1】:

用过这个

1) 替换这个: dataType: jsonp 用于跨域请求,即请求到不同的域和

dataType: json 同域同源请求。 数据类型:“json”

2)成功后缺少','函数

$.ajax({
        type: "get",
        url: url ,
        dataType: "json",
        cache: "false",
        jsonpCallback: "onJSONPLoad",
        success: function(json){
               alert('hi!');
               //perform operation
        },
        error: function() {
          alert('Error occurs!');
       }
});

3) 试试这个

error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert('Not connect.\n Verify Network.');
            } else if (jqXHR.status == 404) {
                alert('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                alert('Time out error.');
            } else if (exception === 'abort') {
                alert('Ajax request aborted.');
            } else {
                alert('Uncaught Error.\n' + jqXHR.responseText);
            }
        }

4) 检查这个jQuery.ajax

json 类型将获取的数据文件解析为 JavaScript 对象,并将构造的对象作为结果数据返回。为此,它在浏览器支持时使用 jQuery.parseJSON();否则它使用 Function 构造函数。格式错误的 JSON 数据将引发解析错误(有关更多信息,请参阅 json.org)。 JSON 数据便于以一种简明且易于 JavaScript 解析的方式传递结构化数据。如果获取的数据文件存在于远程服务器上,请指定jsonp类型。

jsonp类型附加一个callback=?的查询字符串参数?到网址。服务器应在 JSON 数据前面加上回调名称,以形成有效的 JSONP 响应。我们可以使用 $.ajax() 的 jsonp 选项指定回调以外的参数名称。

注意:JSONP 是 JSON 格式的扩展,需要一些服务器端代码来检测和处理查询字符串参数。有关它的更多信息,请参阅详细说明其用途的原始帖子。

从远程服务器检索数据时(只能使用脚本或 jsonp 数据类型),永远不会触发错误回调和全局事件。

但你需要触发然后代码:

var req = $.ajax({
    url : url,
    dataType : "jsonp",
    timeout : 10000
});

req.success(function() {
    console.log('Yes! Success!');
});

req.error(function() {
    console.log('Oh noes!');
});

【讨论】:

  • 谢谢,尝试dataType: "jsonp" 没问题。问题是为什么错误块不起作用。
  • 如果我使用dataType: "json",错误块有效。但是对于有效的 url succes 函数不起作用,因为 url 的数据返回形式是 jsonp 的数据类型。
  • 从远程服务器检索数据时(只能使用脚本或 jsonp 数据类型),永远不会触发错误回调和全局事件。为此检查我的更新答案
  • 如果是这个原因,你知道如何处理我的情况吗?请提出建议。
【解决方案2】:

成功函数后缺少逗号,并将 dataType 更改为 json

$.ajax({
        type: "get",
        url: url ,
        dataType: "json",
        cache: "false",
        jsonpCallback: "onJSONPLoad",
        success: function(json){
               alert('hi!');
               //perform operation
        },
        error: function() {
          alert('Error occurs!');
       }
});

【讨论】:

    【解决方案3】:

    最近在 chrome 52(2016 年 8 月)中引入的错误也可能导致这种行为。 希望不会持续太久。

    https://bugs.chromium.org/p/chromium/issues/detail?id=633696

    它与最初的问题并不严格相关,因为它仅触发从 onSuccess 处理程序启动的 GET 请求,但我提到它以供其他可能搜索此问题帮助的人使用。

    【讨论】:

      【解决方案4】:

      试试这个。

           $.ajax({
                      type: "get",
                      url: url ,
                      dataType: "jsonp",
                      cache: "false",
                      jsonpCallback: "onJSONPLoad",
                      success: function(result){
                             alert('hi!');
                             //perform operation
                      },    
                     error: function( req, status, err ) {
                       console.log( 'something went wrong', status, err );
                       alert('something went wrong'+ status + err); 
                     } 
            });
      

      也读这个。 http://api.jquery.com/jQuery.getJSON/#entry-examples

      然后尝试 $.getJSON() 而不是 $.ajax()

      【讨论】:

        猜你喜欢
        • 2014-03-14
        • 2015-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-04
        • 2012-05-08
        相关资源
        最近更新 更多