简体   繁体   English

如何处理jsonp错误?

[英]How to Handle jsonp errors?

I'm making a jsonp request with jquery.ajax() like this: 我正在使用jquery.ajax()发出jsonp请求,如下所示:

var cep = 99999999;
$.ajax({
    url: "http://cep.paicon.com.br/jsonp/"+ cep +"?callback=addressFunction",
    dataType: 'jsonp',
    crossDomain: true,
    jsonp: false
})

When there alright, the requested page call my callback function normally. 好的时候,被请求的页面通常会调用我的回调函数。

But, in some situations, the requested page don't return anything. 但是,在某些情况下,请求的页面不返回任何内容。

How can i handle this error, since it won't call any callback function? 由于该错误不会调用任何回调函数,我该如何处理?

Thanks! 谢谢!

(Sorry for my poor English) (对不起,我英语不好)

You can't handle that. 你不能处理。 The server must be made to always return some JavaScript, which in the case of an error might be something that calls some pre-arranged error handler function, or whatever seems appropriate. 必须使服务器始终返回一些JavaScript,在发生错误的情况下,该JavaScript可能会调用某些预先安排的错误处理程序函数,或者可能是任何合适的东西。

If your requested page returns nothing, then you need to wrap it in some code so it returns an error code in some JSON. 如果您请求的页面什么都不返回,那么您需要将其包装在某些代码中,以便它在某些JSON中返回错误代码。 So, you could decorate the request service with something that has a timeout and then returns some json that might be: 因此,您可以使用具有超时的内容装饰请求服务,然后返回一些可能是的json:

{
   errorCode: "requestTimeout"
}

You can set a timeout on your $.ajax() call, and handle the lack of response via that mechanism. 您可以在$ .ajax()调用上设置超时,并通过该机制来处理缺少响应的情况。

$.ajax({
  url: "http://cep.paicon.com.br/jsonp/"+ cep +"?callback=addressFunction",
  type: "GET",
  dataType: "jsonp",
  timeout: 2000,
  success: function(response) { alert(response); },
  error: function(x, t, m) {
      if(t==="timeout") {
          alert("got timeout");
      } else {
          alert(t);
      }
  }
});​

I got handle the error with the textStatus == "parsererror" in $.ajax error setting. 我在$ .ajax错误设置中使用textStatus ==“ parsererror”处理错误。

Now my function is like that: 现在我的功能是这样的:

function buscaEndereco(cep){
    url = "http://cep.paicon.com.br/jsonp/"+ cep;
    $.ajax({
       url: url,
       type: "GET",
       dataType: 'jsonp',
       crossDomain: true,
       timeout: 10000,
       success: function(response){ 
           montaEndereco(response); 
       },
       error: function(x, t, m){
           if(t == "timeout"){
           alert("Timeout");
           } else {
            if(t == "parsererror"){
               alert("CEP not found");
            } else {
               alert(t);
            }
           }
       }
    });
}

Thanks 谢谢

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

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