如何知道返回数据是jQuery和PHP中的Json还是String? [英] How to know if return data is Json or String in jQuery and PHP?

查看:73
本文介绍了如何知道返回数据是jQuery和PHP中的Json还是String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在客户端(jQuery)中检查从PHP函数返回的数据是Json对象还是String来分配不同的函数.

I want to check in client side(jQuery) whether return data from a PHP function is Json object or String to assign different function.

推荐答案

如果json的格式不正确,jQuery的parseJson将生成异常.您可以将呼叫包装在try catch块中. (但是请记住,在常规代码流程中包含异常是不好的做法)

jQuery's parseJson will generate an exception if the json is not in the correct format. You could wrap your call in a try catch block. (But remember that having exceptions in your normal code's flow is bad practice)

data = '{}';
try {
    json = $.parseJSON(data);
} catch (e) {
    // not json
}

您还可以使用本机的JSON.parse()方法,该方法会引发SyntaxError异常

You can also use the native JSON.parse() method which throws a SyntaxError exception

如果您希望不良JSON作为正常程序工作流程的一部分,则可以先使用正则表达式进行检查,

If you are expecting bad JSON as part of your normal program workflow then you could check it with regex first, Mic's answer is pretty solid But in your case, PHP should always generate valid json under normal conditions. If its invalid there probably is a bug in your software

这篇关于如何知道返回数据是jQuery和PHP中的Json还是String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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