简体   繁体   English

Convert PHP array of JSON to JavaScript object in AJAX

[英]Convert PHP array of JSON to JavaScript object in AJAX

I am working on a AJAX feature of PHP and JavaScript.我正在研究 PHP 和 JavaScript 的 AJAX 功能。 My PHP code is like below.我的 PHP 代码如下所示。

$volunteers = get_post_meta($_POST[element_id], "volunteers", false);
$users = array();

    foreach ($volunteers as $volunteer) {
        $users[] = ['id'=>$volunteer['ID'], 'text'=>$volunteer['display_name']];
    }

    echo json_encode($users);

    die;

Output of this code is like below.此代码的 Output 如下所示。

在此处输入图像描述

But I need JavaScript Objects like below.但我需要 JavaScript 对象,如下所示。

var data = {
    id: 1,
    text: 'Barn owl'
};

How can I convert PHP arrays to JavaScript Objects?如何将 PHP arrays 转换为 JavaScript 对象?

What you've got there is an array of objects already.您所拥有的已经是一组对象。

So if the response data from the AJAX/PHP is in a variable called response (and has been parsed with JSON.parse ) then var data = response[0] will give you the first object in the list, and it will put it into the data variable, and it will have the structure you've requested (because it already has that when it's stored in the array - all we're doing here is copying it to a separate variable).因此,如果来自 AJAX/PHP 的响应数据位于名为response的变量中(并且已使用JSON.parse解析),那么var data = response[0]将为您提供列表中的第一个 object,并将其放入data变量,它将具有您请求的结构(因为它在存储在数组中时已经具有该结构 - 我们在这里所做的只是将其复制到一个单独的变量中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM