$.each() 迭代字符串中的字符 - 我需要 eval() 吗?
我有 json 数据作为集合返回:
var foo = ["6", "7", "33"]
在 jQuery 中使用 JSONP。由于我使用的是 JSONP,数据将返回到回调函数,该函数将其解释为字符串而不是集合。在将回调中的字符串作为集合处理之前,我是否需要对其运行 eval(foo)
,或者是否有其他方法可以对其进行重铸?
I have json data being returned as a collection:
var foo = ["6", "7", "33"]
using JSONP in jQuery. Since I'm using JSONP, the data is being returned to a callback function, which is interpreting it as a string instead of a collection. Do I need to run eval(foo)
on the string in the callback before handling it as a collection, or is there some other means of recasting it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用的是 jQuery,则应该使用
dataType: "jsonp"
执行.ajax
,这应该将解析后的数据发送到您的回调,而不是字符串。如果这对您不起作用,或者还有我没有看到的其他复杂性,您可以使用$.parseJSON(foo)
而不是eval(foo)
。如果存在,这将调用浏览器的本机JSON.parse
方法,如果不存在,则使用eval
。If you're using jQuery, you should be doing
.ajax
withdataType: "jsonp"
, which should send the parsed data to your callback, rather than a string. If this doesn't work for you, or there are other complexities I'm not seeing, you can use$.parseJSON(foo)
instead ofeval(foo)
. This will call the browser's nativeJSON.parse
method if it exists, or useeval
if it doesn't.