簡體   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