AJAX:检查是否字符串是JSON? [英] AJAX: Check if a string is JSON?
本文介绍了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?
我不希望使用一个框架 - 有什么办法,使只使用评估这项工作()
? (有一个很好的理由,我保证。)
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解析器。组织,你可以用它的parse()函数,只是把它包在一个try / catch,像这样:
If you include the JSON parser from json.org, you can use it's 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屋!
查看全文