通过 AJAX 和 jQuery 从 PHP 数组中获取数据 [英] Get data from PHP array via AJAX and jQuery

查看:36
本文介绍了通过 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 请求;

and a php file ajax.php to handle ajax requests as;

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

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

But when I click, I am getting A instead of array[0]. How can I fix this?

推荐答案

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

you cannot access array (php array) from js try

<?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]);
            },
        });
    });
});

这篇关于通过 AJAX 和 jQuery 从 PHP 数组中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆