繁体   English   中英

使用json_encode()将PHP数组转换为JavaScript数组

[英]PHP array to JavaScript array using json_encode()

如何将数组从PHP传递到JavaScript函数console.log() 我正在模拟一个数据库。 我知道我在代码中没有声明数组。 我试过使用.getJSON()函数,但是没有用。 我应该为每个元素进行AJAX调用吗? 我当时在想,但必须有更好的方法。

JavaScript代码:

$.ajax({
         method:"POST",
         url:'php.php',
         data:"",
         dataType:'json',
         success:function(data){
             var y1=data;
             console.log(data.name);
         }
      });

PHP代码:

<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


if($_SERVER["REQUEST_METHOD"] == "POST")
{
    //assign vars after formatting to avoid a wrong login with correct 
    //username and password
    $username = trim($_POST["user"]);


   $customer_array = array();

    $customer1 = array(
        'name' => '3',
        'city' => 'Houston'
    );

    $customer_array[] = $customer1;

    $customer2 = array(
        'name' => '2',
        'city' => 'Boston'
    );

    $customer_array[] = $customer2;

    $customer3 = array(
        'name' => "1",
        'city' => "Bossier City"
    );

    echo json_encode($customer_array);
}

我只是将我的评论总结成一个答案,首先,我将关闭json返回以解决问题。 您仍然可以在事实之后解析json:

$.ajax({
    // Do "type" here
    type:"POST",
    url:'php.php',
    // Send something to check in the script
    // This is optional, but I like to do it...
    data: {
        "action":"get_name_city"
    },
    success:function(data){
        // Do a try, just incase your parse fails
        try {
            // Parse the json here
            var getJson = JSON.parse(data);
            console.log(getJson);
            console.log(data);
        }
        catch(Exception) {
            // Show any errors that might get thrown
            console.log(Exception.message);
        }
    }
});

PHP:

# Check the action is set and is named
if(isset($_POST["action"]) && $_POST["action"] == "get_name_city") {
    $username = trim($_POST["user"]);
    $customer_array = array();

    $customer1 = array(
        'name' => '3',
        'city' => 'Houston'
    );

    $customer2 = array(
        'name' => '2',
        'city' => 'Boston'
    );

    $customer3 = array(
        'name' => "1",
        'city' => "Bossier City"
    );

    $customer_array[] = $customer1;
    $customer_array[] = $customer2;
    $customer_array[] = $customer3;

    # Just die here
    die(json_encode($customer_array));
}
# Die with error so there is some feedback to your ajax
die(json_encode(array('error'=>'No data was sent.')));

你几乎在那里。 您的AJAX请求接受JSON,但您的PHP不输出JSON(它会以正确的方式,但不会以正确的方式输出),您必须设置适当的Content-Type标头:

header('Content-Type: application/json');
echo json_encode($customer_array);

现在,您的AJAX请求应该能够使用格式正确的JSON作为data变量(并console.log它)。

如前所述,有多种方法可以从PHP传递数据:

  • 在将返回值从json_encode()发送到echo()之前,将Content-Type标头添加为application / json值:

     header('Content-Type: application/json'); echo json_encode($customer_array); 
  • 使用JSON.parse()解析PHP的返回值

     success:function(data){ var y1=data; var data = JSON.parse(data); 

因此,选择其中一种方法。 有人可能会说第一个在语义上更正确,因为正在发送JSON数据。

此外,AJAX请求的成功回调正在尝试访问返回数据的属性名称 但是,返回的数据应该是一个对象数组,每个对象都有一个属性 记录每个属性名称的一种方法是使用Array.forEach()并将数组中每个元素的名称发送到console.log()

data.forEach(function(dataItem) {
    console.log(dataItem.name);
});

此phpfiddle中查看对此的演示

暂无
暂无

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

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