在我的 php 代码中,我回显变量的对象类型。然而,在JQuery ajax中成功返回的数据是String数据的形式。我正在使用 JSON.parse(data) 将数据解析为 JSON 形式。但由于返回字符串数据的格式,我无法做到这一点。我可以知道如何在 php 中返回 JSON 对象,同时在我的 JQuery $ajax 函数中也将获取 JSON 对象而不是字符串。以下是我的代码。
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";
}
?>
最佳答案
在 ajax 调用中添加 dataType:'json'
你必须让他知道你从ajax调用中得到什么样的数据。此外,如果你的条件失败,发送一个数组,像这样
json_encode(array('state'=>'nothing'));
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(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);
}
})
});
关于javascript - JQuery Ajax 在 javascript 中获取不同类型的变量与 PHP 相比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39605664/