javascript - 通过 AJAX 和 jQuery 从 PHP 数组中获取数据

我有一个页面如下:

<head>
<script type="text/javascript" src="jquery-1.6.1.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('#prev').click(function() {
  $.ajax({
  type: 'POST',
  url: 'ajax.php',
  data: 'id=testdata',
  cache: false,
  success: function(result) {
    $('#content1').html(result[0]);
  },
  });
});
});
</script>
</head>
<body>
<table>
<tr>
<td id="prev">prev</td>
<td id="content1">X</td>
<td id="next">next</td>
</tr>
</table>
</body>

和一个php文件ajax.php来处理ajax请求;

<?php
$array = array(1,2,3,4,5,6);
echo $array;
?>

但是当我点击时,我得到的是 A 而不是数组 [0]。我该如何解决这个问题?

最佳答案

你不能从 js 访问数组(php 数组) 试试

<?php
$array = array(1,2,3,4,5,6);
echo json_encode($array);
?>

和js

$(document).ready( function() {
    $('#prev').click(function() {
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: 'id=testdata',
            dataType: 'json',
            cache: false,
            success: function(result) {
                $('#content1').html(result[0]);
            },
        });
    });
});

https://stackoverflow.com/questions/6395720/

相关文章:

javascript - 无法重新初始化 JQuery DataTable

c# - 分配给单个属性的多个 JsonProperty 名称

c++ - JSONCPP 写入文件

javascript - 来自json对象的Angular.js格式日期

json - 已启用 CORS,但在 POST JSON 时,预检响应的 HTTP 状态代码 404

java - 如何在 JAVA 中对 JSONArray 进行排序

ruby-on-rails - 为什么在 Ubuntu 中安装 JSON gem 时会出错?

eclipse - Jersey :找不到 Java 类和 MIME 媒体类型应用程序/json 的

c# - 如何使用 C#/LINQ 将 XML 转换为 JSON?

javascript - 如何在 javascript/jquery 中构建 json 字符串?