开发者

Parsing JSONP Response in Javascript when 4xx or 5xx Http Error Code is Present

开发者 https://www.devze.com 2023-02-17 13:22 出处:网络
I am implementing an application which relies upon communication between a JavaScript client and a server which knows how to respond to the client using JSONP notation.

I am implementing an application which relies upon communication between a JavaScript client and a server which knows how to respond to the client using JSONP notation.

I am attempting to handle the case in my Javascript client where my server return开发者_如何学Gos with an http status code of 4xx or 5xx. Currently what I'm seeing is that the script is not evaluated as the browser believes it to be an error (which it is.) However, I still want to read what my server has to say in the event of this 4xx or 5xx response code in my JavaScript client.

I'm seeing that this does raise an error on the script tag element, but I'm concerned that this is not cross browser and will not be a robust solution.

Has anyone had any luck on still parsing a jsonp response even though the http status code is 4xx or 5xx?

I'm beginning to believe I should just use this "set a timeout" solution which "detects" a failure by stating the callback function to the jsonp request would complete within a certain time frame, and if it doesn't, there was an error.

EDIT: I'm temporarily always returning 200 status code when my server detects a jsonp client and then tunneling the error message/status in the json object returned. I was hoping to take advantage of the HTTP status codes but I'm thinking that is no-go for a javscript client.


JSONP is a hack to work-around cross-domain issues. When it works, it works well. But when it doesn't you don't have a way to figure out what went wrong.

setTimeout is another hack on top of the original one. If you must use JSONP and still need error detection (not handling), thats what you'd have to do. There isn't a better solution.

If you control the server, try to use alternatives such as Cross-Origin-Resource-Sharing (CORS), or Flash's crossdomain.xml to allow cross domain requests. If you don't control the server, you can proxy the response through your server to get better control.


One approach when using JSONP is to embed status information in the callback. So the callback function signature would look like

callback(result, status, message)

So if your call looks like

http://myurl.com/?callback=fn

generate code for a successful call that looks like

fn({"data":"my great data"}, 200)

and for an exceptional condition

fn(null, 500, "server error"}


You can check the status of the XHR object (if you are not using a JS library).

if(xhr.readyState == 4){
  if(xhr.status == 200){
    // good
  }else if(xhr.status == 502){
    // d'oh
  }
}

If you are using jQuery, you can pass in a statusCode to handle special cases for $.ajax

0

精彩评论

暂无评论...
验证码 换一张
取 消