我正在尝试从 PHP 页面获取 JSON,但总是收到“未定义”。
我的 jQuery 代码是:
<script>
$(document).ready(function(){
$("#lista_partecipanti").click(function(){
$.post( "application/third_party/php_files/lista_partecipanti.php",
{
user_id:<? echo $user_id; ?> , jam_id:<? echo $id_jam; ?>
},
function(data)
{
if(data) {
$("#div_lista_partecipanti").html('test' + data[0].username);
}
else
{
alert("Error");
}
});
});
});
</script>
我的 PHP 代码是:
<?php
include 'db_connect.php';
$a_id = $_POST['user_id'];
$b_id = $_POST['jam_id'];
$query = mysql_query("SELECT * FROM User a, Jam b WHERE a.id = b.owner AND a.id = $a_id AND b.id = $b_id");
if(mysql_num_rows() == 1)
{
$row = mysql_fetch_assoc($query);
$data = array(
'username' =>$row['username'],
'user_id' => $row['id']
);
$data = json_encode($data);
echo $data;
}
else
return false;
mysql_close();
?>
解决了
我解决了我的问题,这不是 PHP 问题,但错误在 jquery 代码中。我刚刚添加
data = $.parseJSON(data);
前
$("#div_lista_partecipanti").html(data.username);