AJAX:检查字符串是否为 JSON? [英] AJAX: Check if a string is JSON?

查看:44
本文介绍了AJAX:检查字符串是否为 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 JavaScript 有时会在这一行崩溃:

My JavaScript sometimes crashes on this line:

var json = eval('(' + this.responseText + ')');

eval() 的参数不是 JSON 时会导致崩溃.在进行此调用之前,有什么方法可以检查字符串是否为 JSON?

Crashes are caused when the argument of eval() is not JSON. Is there any way to check if the string is JSON before making this call?

我不想使用框架 - 有什么方法可以仅使用 eval() 来完成这项工作?(我保证有一个很好的理由.)

I don't want to use a framework - is there any way to make this work using just eval()? (There's a good reason, I promise.)

推荐答案

如果包含 JSON 解析器 来自 json.org,您可以使用它的 parse() 函数并将其包装在 try/catch 中,如下所示:

If you include the JSON parser from json.org, you can use its parse() function and just wrap it in a try/catch, like so:

try
{
   var json = JSON.parse(this.responseText);
}
catch(e)
{
   alert('invalid json');
}

这样的事情可能会做你想做的事.

Something like that would probably do what you want.

这篇关于AJAX:检查字符串是否为 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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