php Ajax - 如何在成功函数中使用返回的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19503631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:35:25  来源:igfitidea点击:

Ajax - How to use a returned array in a success function

javascriptphpjqueryajaxarrays

提问by Matt9Atkins

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 代码。我希望能够在我的 ajax 成功函数中使用这个数组,但我不知道如何去做。我已经尝试了以下,但没有运气。

php code:

php代码:

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

exit($arr);

js code:

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

回答by Hugo Tunius

You should return the data as JSON from the server.

您应该从服务器以 JSON 形式返回数据。

PHP

PHP

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

echo json_encode($arr);
exit();

JS

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

回答by robby

A small mistake:

一个小错误:

Not: exit($arr);

不是: exit($arr);

replace with: echo json_encode($arr);

用。。。来代替: echo json_encode($arr);

回答by Tomas Grecio Ramirez

There a Problem , when you want display for example data[0]and data[1], it seems like a character from string. It Solves adding header("Content-Type: application/json");before apply echo json_encode($arr)

有一个问题,当你想要显示例如data[0]and 时data[1],它看起来像是字符串中的一个字符。它解决了header("Content-Type: application/json");在申请前添加 echo json_encode($arr)

回答by Waqas Qayum

Here is solution

这是解决方案

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

header("Content-Type: application/json");

echo json_encode($arr);

exit();

instead of

代替

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

exit($arr);