Ajax - 如何在成功函数中使用返回的数组 [英] Ajax - How to use a returned array in a success function

查看:77
本文介绍了Ajax - 如何在成功函数中使用返回的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回数组的 php 代码.我希望能够在我的 ajax 成功函数中使用这个数组,但我不知道如何去做.我尝试了以下方法,但没有成功.

Hi I have a php code that returns an array. I want to be able to use this array in my ajax success function but I'm not sure how to go about doing this. I have tried the following, but no luck.

php 代码:

$arr = array();
$arr[0] = "Mark Reed"
$arr[1] = "34";
$arr[2] = "Australia";

exit($arr);

js 代码:

$.ajax({
    type: "POST",
    url: "/returndetails.php",
    data: 'id=' + userid,
    success: function (data) {
        document.getElementById("name").innerHTML = data[0];
        document.getElementById("age").innerHTML = data[1];
        document.getElementById("location").innerHTML = data[2];
    }
});

推荐答案

您应该从服务器以 JSON 格式返回数据.

You should return the data as JSON from the server.

PHP

$arr = array();
$arr[0] = "Mark Reed";
$arr[1] = "34";
$arr[2] = "Australia";

echo json_encode($arr);
exit();

JS

$.ajax({
    type: "POST",
    url: "/returndetails.php",
    data: 'id=' + userid,
    dataType: "json", // Set the data type so jQuery can parse it for you
    success: function (data) {
        document.getElementById("name").innerHTML = data[0];
        document.getElementById("age").innerHTML = data[1];
        document.getElementById("location").innerHTML = data[2];
    }
});

这篇关于Ajax - 如何在成功函数中使用返回的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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