[英]Send array from php to js with ajax and json
我正在尝试从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);
});
});
});
这是我使用的第一个应用程序,因此,请耐心等待。
现在,您将发送完整的页面标记以及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;
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.