简体   繁体   中英

JQuery Ajax Get different type of variable in javascript compare with PHP

In my php code, I echo object type of variable. However, in JQuery ajax success return data is in the form of String data. I am using JSON.parse(data) to parse data into JSON form. But I can't do it due to the format of return string data. May I know how can I return JSON object in php and at the same the in my JQuery $ajax function will get the JSON object also and not string. The following is my code.

Javascript:

$(document).ready(function callAjax(){
        $.ajax({
            type: "GET",
            url: "php/test.php",
            cache: false,
            success: function(data){
                console.log( data);
                 interval = setTimeout(callAjax, 1000);  
            }
        })
});

PHP:

<?php
    require('test2.php');

   $messages = get_msg();
    if (is_array($messages) || is_object($messages)){
        foreach($messages as $message){
      $array = array('chat_id' => $message['chat_id'], 
                    'sender_name' => $message['sender_name'],
                    'chat_body' => $message['chat_body'], 
                    'chat_time' => $message['chat_time']);
      $object = (object) $array;
            echo json_encode(gettype ($object));
        }
    }else{
        echo "Nothing";
    }
?>

Add dataType:'json' inside your ajax call

You have to let him know what kind of data you are getting from the ajax call.Further more, send an array if your condition fails , something like this

json_encode(array('state'=>'nothing'));

php code

 require('test2.php');

   $messages = get_msg();
    if (is_array($messages) || is_object($messages)){
        foreach($messages as $message){
      $array = array('chat_id' => $message['chat_id'], 
                    'sender_name' => $message['sender_name'],
                    'chat_body' => $message['chat_body'], 
                    'chat_time' => $message['chat_time']);
      $object = (object) $array;
            echo json_encode(array('state'=>gettype($object)));
        }
    }else{
        echo json_encode(array('state'=>'nothing'));
}

Javascript

$(document).ready(function callAjax(){
        $.ajax({
            type: "GET",
            url: "php/test.php",
            cache: false,
            dataType:'json',
            success: function(data){
                 try {
                    data = jQuery.parseJSON(data);
                  }
                  catch (err) {
                     data = typeof data == 'object' ? data : jQuery.parseJSON(data);
                }
                 console.log(data.state);
                 interval = setTimeout(callAjax, 1000);  
            }
        })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM