简体   繁体   English

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

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

How do I pass an array from PHP to the JavaScript function console.log() ? 如何将数组从PHP传递到JavaScript函数console.log() I'm simulating a DB. 我正在模拟一个数据库。 I understand that I don't have an array declared in the code. 我知道我在代码中没有声明数组。 I've tried using the .getJSON() function but it didn't work. 我试过使用.getJSON()函数,但是没有用。 Should I do an AJAX call for each element? 我应该为每个元素进行AJAX调用吗? I was thinking about that but there has to be a better way. 我当时在想,但必须有更好的方法。

JavaScript code: JavaScript代码:

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

PHP code: 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);
}

I am just going to summarize my comments into an answer, first I would just turn off the json return for trouble shooting. 我只是将我的评论总结成一个答案,首先,我将关闭json返回以解决问题。 You can parse the json after fact anyway: 您仍然可以在事实之后解析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: 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.')));

You where almost there. 你几乎在那里。 Your AJAX requests accepts JSON but your PHP does not output JSON (it does but not in the correct way), you'll have to set the appropriate Content-Type header: 您的AJAX请求接受JSON,但您的PHP不输出JSON(它会以正确的方式,但不会以正确的方式输出),您必须设置适当的Content-Type标头:

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

Your AJAX request should now be able to use the properly formatted JSON as the data variable (and console.log it). 现在,您的AJAX请求应该能够使用格式正确的JSON作为data变量(并console.log它)。

As has been mentioned, there are multiple options for passing the data from PHP: 如前所述,有多种方法可以从PHP传递数据:

  • add the Content-Type header with value application/json before sending the return from json_encode() to echo() : 在将返回值从json_encode()发送到echo()之前,将Content-Type标头添加为application / json值:

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

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

So pick one of those approaches. 因此,选择其中一种方法。 One might argue that the first is more semantically correct, since JSON data is being sent. 有人可能会说第一个在语义上更正确,因为正在发送JSON数据。

Additionally, the success callback of the AJAX request is attempting to access the property name of the data returned. 此外,AJAX请求的成功回调正在尝试访问返回数据的属性名称 However, the data returned should be an array of objects, each which has a property name . 但是,返回的数据应该是一个对象数组,每个对象都有一个属性 One approach to logging the name of each property is to use Array.forEach() and send the name of each element in the array to console.log() . 记录每个属性名称的一种方法是使用Array.forEach()并将数组中每个元素的名称发送到console.log()

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

See a demonstration of this in this phpfiddle . 此phpfiddle中查看对此的演示

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

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