php 如何知道jQuery和PHP中的返回数据是Json还是String?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3945499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:31:35  来源:igfitidea点击:

How to know if return data is Json or String in jQuery and PHP?

phpjquery

提问by Devyn

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

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

回答by Yarek T

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)

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

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

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

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

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 solidBut in your case, PHP should always generate valid json under normal conditions. If its invalid there probably is a bug in your software

如果您希望将错误的 JSON 作为正常程序工作流程的一部分,那么您可以先使用正则表达式检查它,Mic 的答案非常可靠但在您的情况下,PHP 应始终在正常条件下生成有效的 json。如果它无效,则可能是您的软件中存在错误

回答by FatherStorm

try {
   jQuery.parseJSON( json )
   //must be valid JSON
} catch(e) {
    //must not be valid JSON    
}

回答by Nikita Rybak

Return data is always a string (i.e., a character sequence). But, if you tell jQuery you expect json response, it'll attempt to convert string into a javascript object for you.
There's no dedicated network protocol to transfer javascript objects over the internet.

返回数据始终是字符串(即字符序列)。但是,如果您告诉 jQuery 您期望 json 响应,它会尝试为您将字符串转换为 javascript 对象。
没有专门的网络协议来通过互联网传输 javascript 对象。

回答by orolo

In javascript, you can use typeof

在javascript中,你可以使用typeof