当存在4xx或5xx Http错误代码时,在Javascript中解析JSONP响应 [英] Parsing JSONP Response in Javascript when 4xx or 5xx Http Error Code is Present

查看:296
本文介绍了当存在4xx或5xx Http错误代码时,在Javascript中解析JSONP响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个依赖于JavaScript客户端和服务器之间通信的应用程序,该服务器知道如何使用JSONP表示法响应客户端。

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.

我正在尝试处理我的Javascript客户端中的情况,我的服务器返回的状态代码为4xx或5xx。目前我所看到的是脚本没有被评估,因为浏览器认为它是一个错误(它是。)但是,我仍然想要阅读我的服务器在4xx或5xx响应的情况下要说的内容我的JavaScript客户端中的代码。

I am attempting to handle the case in my Javascript client where my server returns 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.

即使http状态代码是4xx或5xx,有没有人还在解析jsonp响应?

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

我开始相信我应该使用这个设置超时解决方案,通过声明jsonp请求的回调函数将在特定时间范围内完成来检测失败,如果它没有,出现错误。

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.

编辑:当我的服务器检测到jsonp客户端然后隧道传输错误消息时,我暂时总是返回200状态代码返回的json对象中的状态。我希望利用HTTP状态代码,但我认为javscript客户端是不行的。

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时的一种方法是在回调中嵌入状态信息。所以回调函数签名看起来像

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)

和特殊情况

fn(null, 500, "server error"}

这篇关于当存在4xx或5xx Http错误代码时,在Javascript中解析JSONP响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆