javascript - 使用ajax和json将数组从php发送到js

标签 javascript php ajax json mysqli

我正在尝试从 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;
?>

关于javascript - 使用ajax和json将数组从php发送到js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31096743/

相关文章:

php - 如何使用ajax和php将100个对象保存到服务器?

javascript - 通过Ajax动态更新数据列表

PHP 在 HTML 表格中显示数组

php - 在php中按值对多维数组进行分组

php - 为什么 mysqli 和 PDO 给出不同的结果

ajax - 对基于类的 View 进行 AJAX POST

Jquery Ajax 动画?

javascript - 如何在 jquery 中向上或向下移动表行时修复特定列值

javascript - Flask+AJAX+Jquery+JINJA动态更新HTML Table

javascript - 使用 html 字符串中的 id 获取名称的正则表达式