如何在jQuery post方法中检查从PHP返回的数据类型

Type of data

[{"id":"1","value":"Google"},{"id":"2","value":"Samsung"}]

Now I have a general function that performs certain actions based on the type of data being returned.

for this particular data I am checking if it is array or not. In order to check the type of the data being return I am using the following custom function.

function typeOf (obj) {
  return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}

now if I call typeOf(1) it returns "number" as answer

if I call typeOf("foo") it return "string" as answer

The Problem

calling typeOf(data) where data = [{"id":"1","value":"Google"},{"id":"2","value":"Samsung"}] being echoed from php page it gives "string" as answer

It only returns array if the recieved array type data variable is passed through following function as

data = jQuery.parseJSON(data);

Now, I understand it might be the case that what ever gets echoed from php comes in string form but isn't there any way it can be changed as my php page is doing following

echo json_encode(array(array(some_key=>some_data)));

For jQuery to know that you're sending JSON data, the server has to respond with the correct Content-Type header. In PHP, this can easily be achieved by calling header('Content-Type: application/json'); before any output, and jQuery will attempt to parse the response.

This will result in the data parameter of your success handler to be an object containing the values from the JSON. Make sure to check that you get an object type data variable, because any other type should indicate that malformed JSON data is coming from your server.

$.ajax({
    url: '/endpoint.php',
    method: "POST",
    data: {key:'value'},
    success: function(data){
        if (typeof data !== 'object')
            return console.error('Invalid data', data);

        // Do something with the response
    }
});

Whatever the value you get as a result of AJAX call, from PHP or JSP, will return it as String. You need to parse the string to make the script to understand the datatype correctly. You can do something like this:

data = JSON.parse(data);

if (typeof data == "object") {
  // JSON Data
} else {
  // String Data
}

Snippet

* {font-family: 'Segoe UI';}
<script>
  function parseData(data) {
    if (data.length > 0)
      data = JSON.parse(data);
    if (typeof data == "object")
      return "This is JSON with keys.";
    else
      return "This is a String of " + data.length + " characters.";
  }
</script>
<p><strong>JSON Object</strong></p>
<p><script>document.write(parseData('{"a": "Alphabet", "b": "Fun"}'));</script></p>
<p><strong>String / Number</strong></p>
<p><script>document.write(parseData(''));</script></p>

</div>

I'm assuming you're getting that data via ajax. Have you specified dataType: 'json' in the ajax function? If no dataType is specified, jQuery will guess, and sometimes, it guesses wrong.

(Edit: More on the $.ajax function here: http://api.jquery.com/jquery.ajax/ )