Hi, I want to check in client side(jQuery) whether return data from a PHP function is Json object or String to assign different function.
How to tell if `typeof(A) != typeof(B)`, where `A` and `B` are strings...? :-)
pst
2010-10-15 19:42:17
Thanks for yr advice but typeof is not working for my example :)
Devyn
2010-10-15 19:46:42
+4
A:
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.
Nikita Rybak
2010-10-15 19:39:51
+2
A:
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
}
Yarek T
2010-10-15 19:43:52
Thanks for your fast reply but I'm a little confuse with bad practice. You mean I shouldn't try to solve my problem with parseJSON's exception?
Devyn
2010-10-15 19:51:15
No, firing exceptions in normal execution is a bad practice. Exeptions should only be fired when something is wrong (when you don't expect some result)
Yarek T
2010-10-15 19:52:04
+3
A:
try {
jQuery.parseJSON( json )
//must be valid JSON
} catch(e) {
//must not be valid JSON
}
FatherStorm
2010-10-15 19:45:24