gpt4 book ai didi

javascript - PHP json_encode 函数不适用于 ajax 调用

转载 作者:行者123 更新时间:2023-11-30 08:40:17 25 4
gpt4 key购买 nike

在页面加载中我调用这个函数

function myFunction(selectedCinemaID) {    
$.ajax({
type: "POST",
url: "show_details.php",
data: {cinema_id: selectedCinemaID }
}).done(function( show_list ) {
console.log(show_list.length);

});

我的代码在 show_details.php 中

$query = "SELECT * FROM `show` WHERE cinema_id=2;";
$result = mysql_query($query);

if($result){
$show_list = array();
while($row = mysql_fetch_array($result)){
array_push ($show_list, array($row['id'], $row['cinema_id'], row['show_time']));
}
echo json_encode($show_list);
} else {
echo mysql_error();
}

在我的数据库中,我只有两行三列,但控制台显示的长度是 64。但根据数据库长度应该是 2。console.log(show_list) output [["2", "2","2014-11-01 01:00:00"],["3","2","2014-11-01 04:00:00"]] 但似乎一切都在这里被视为数组元素或字符串。这段代码有什么问题?

最佳答案

您还没有告诉 jquery 您正在发送 JSON。因此,它将服务器发送的 json 文本视为文本。这意味着

    console.log(show_list.length);

正在输出 json 字符串的长度,而不是您在 PHP 中构建的数组的计数/大小。

你需要一个

$.getJSON(....);

$.ajax( 
dataType: 'json'
...
)

但是,请注意,如果您的 mysql 查询由于任何原因失败,那么按照您的原样输出 mysql 错误消息将导致 jquery 出错 - 它需要 JSON,并且您可能会向它发送 mysql 错误消息,这绝对不是 json。

一旦你切换到 JSON 模式,除了 json 之外,你不应该发送任何其他东西:

if (query ...)
output json results
} else {
echo json_encode(array('error' => mysql_error()));
}

关于javascript - PHP json_encode 函数不适用于 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27196128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com