[英]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.