我有一个简单的AJAX调用,服务器将返回一个带有有用数据的JSON字符串或一个由PHP函数mysql_error()产生的错误消息字符串。如何测试该数据是JSON字符串还是错误消息。
使用一个名为isJSON的函数会很好,就像你可以使用instanceof函数来测试某个东西是否是数组一样。
这就是我想要的:
if (isJSON(data)){
//do some data stuff
}else{
//report the error
alert(data);
}
嗯…这取决于你接收数据的方式。我认为服务器正在响应一个JSON格式
字符串(在PHP中使用json_encode(),例如)。如果你正在使用JQuery post并将响应数据设置为JSON格式,并且它是一个格式错误的JSON,这将产生一个错误:
$.ajax({
type: 'POST',
url: 'test2.php',
data: "data",
success: function (response){
//Supposing x is a JSON property...
alert(response.x);
},
dataType: 'json',
//Invalid JSON
error: function (){ alert("error!"); }
});
但是,如果你使用类型响应作为文本,你需要使用$. parsejson。根据jquery网站:
“传递一个格式错误的JSON字符串可能导致抛出异常”。因此你的代码将是:
$.ajax({
type: 'POST',
url: 'test2.php',
data: "data",
success: function (response){
try {
parsedData = JSON.parse(response);
} catch (e) {
// is not a valid JSON string
}
},
dataType: 'text',
});
我用了这个(有点混合了不同的答案,但不管怎样):
const isJSON = str => {
If (typeof STR === 'string'){
尝试{
JSON.parse (str)
还真
}捕捉(e) {
}
}
返回假
}
[null, undefined, false, true, [], {},
”,“asdf ', '{}', '[]', "{\" abc \”:2}”、“{\“abc \”,\“2 \“}”)
.map(el => {
console.log(' [>${el}<] - ${isJSON(el)} ')
})
console.log ('-----------------')
嗯…这取决于你接收数据的方式。我认为服务器正在响应一个JSON格式
字符串(在PHP中使用json_encode(),例如)。如果你正在使用JQuery post并将响应数据设置为JSON格式,并且它是一个格式错误的JSON,这将产生一个错误:
$.ajax({
type: 'POST',
url: 'test2.php',
data: "data",
success: function (response){
//Supposing x is a JSON property...
alert(response.x);
},
dataType: 'json',
//Invalid JSON
error: function (){ alert("error!"); }
});
但是,如果你使用类型响应作为文本,你需要使用$. parsejson。根据jquery网站:
“传递一个格式错误的JSON字符串可能导致抛出异常”。因此你的代码将是:
$.ajax({
type: 'POST',
url: 'test2.php',
data: "data",
success: function (response){
try {
parsedData = JSON.parse(response);
} catch (e) {
// is not a valid JSON string
}
},
dataType: 'text',
});