好吧我可能有一些我无法找到的语法问题,但我认为还有其他问题。
我有一个.php文件,它从数据库中选择多个值,而这个结果是'echo'回到它来自的ajax调用。
.php看起来像这样:
<?php
require("../config/db.php");
$db = mysql_connect(DB_HOST, DB_USER, DB_PASS)or die("Error connecting to database.");
mysql_query("SET NAMES UTF8");
mysql_select_db(DB_NAME, $db)or die("Couldn't select the database.");
$query = "SELECT online_users, chat_messages, cards_order FROM track_changes LIMIT 1";
$result = mysql_query($query, $db) or die(mysql_error().': '.$query);
$row = mysql_fetch_array($result);
$changes = array('online_users'=>$row['online_users'],
'chat_messages'=>$row['chat_messages'],
'cards_order'=>$row['cards_order']);
echo json_encode($changes, JSON_FORCE_OBJECT);
?>
比jQuery ajax调用看起来像这样:
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '/kanbannew/php_scripts/track_changes.php',
data: { },
async: false,
success: function (data) {
console.log(data);
var users = data.online_users;
var chat = data.chat_messages;
var cards = data.cards_order;
console.log("Online users: " + users + "\nChat messages: " + chat + "\nCards order: " + cards);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // ajax end
});
问题出在我获得密钥的第一个警报:像
这样的值{"online_users":"0","chat_messages":"0","cards_order":"0"}
但在第二个警报中,我的每个值都未定义:
Online users: undefined
Chat messages: undefined
Cards order: undefined
此印刷品来自铬conzole。 任何想法为什么我不能访问零的??
答案 0 :(得分:2)
添加dataType。
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '/kanbannew/php_scripts/track_changes.php',
data: { },
dataType: 'json',
async: false,
success: function (data) {
console.log(data);
var users = data.online_users;
var chat = data.chat_messages;
var cards = data.cards_order;
console.log("Online users: " + users + "\nChat messages: " + chat + "\nCards order: " + cards);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // ajax end
});
答案 1 :(得分:1)
您可以添加
header('Content-type: application/json');
到您的PHP代码(在回显任何内容之前)以获得相同的结果,如果您希望您的代码被第三方使用,那么这将有所帮助。但我肯定会添加dataType以及alexey建议