我正在尝试从php发送一个数组(我从mysql表中发送到js)。虽然有很多例子,但我似乎无法使其中的任何一个工作。我到目前为止所获得的代码是:
php_side.php
<!DOCTYPE html>
<html>
<body>
<?php
//$q = intval($_GET['q']);
header("Content-type: text/javascript");
$con = mysqli_connect("localhost","root","","Tileiatriki");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
//mysqli_select_db($con,"users_in_calls");
$sql="SELECT * FROM users_in_calls";
$result = mysqli_query($con,$sql);
/*while($row = mysqli_fetch_array($result)) {
echo $row['User1_number'];
echo "<br/>";
echo $row['User2_number'];
echo "<br/>";
echo $row['canvas_channel'];
echo "<br/>";
}*/
echo json_encode($result);
mysqli_close($con);
?>
</body>
</html>
test_ajax.html
$(document).ready(function(){
$.getJSON('php_side.php', function(data) {
$(data).each(function(key, value) {
// Will alert 1, 2 and 3
alert(value);
});
});
});
这是我第一个使用此类内容的应用程序,请耐心等待。
答案 0 :(得分:1)
现在您正在发送与您的json响应混合的完整页面标记,这当然不起作用。
例如,假设你有以下PHP脚本,它假设返回一个json响应:
<div><?php print json_encode(array('domain' => 'example.com')); ?></div>
此页面的响应不是json,因为它也会返回包装div元素。
您可以将您的PHP代码移动到页面顶部或只删除所有html:
<?php
// uncomment the following two lines to get see any errors
// ini_set('display_errors', 1);
// error_reporting(E_ALL);
// header can not be called after any output has been done
// notice that you also should use 'application/json' in this case
header("Content-type: application/json");
$con = mysqli_connect("localhost","root","","Tileiatriki");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT * FROM users_in_calls";
$result = mysqli_query($con,$sql);
// fetch all rows from the result set
$data = array();
while($row = mysqli_fetch_array($result)) {
$data[] = $row;
}
mysqli_close($con);
echo json_encode($data);
// terminate the script
exit;
?>