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

时间:2017-06-04 05:14:25

标签: javascript php jquery arrays ajax

如何将数组从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);
}

3 个答案:

答案 0 :(得分:1)

我只是将我的评论总结为一个答案,首先我会关闭it == 2问题回复。你无论如何都可以解析json:

import time
import re

cls=("\n" * 50)

fname=input("Please enter your first name:: ")
lname=input("Please enter your last name:: ")

while True:
    age= str (input("Please enter your age:: "))
    if re.search('[0-9]', age):
        break

while True:

    print("Welcome to python ",fname," ",lname,", your current age is ",age, sep="", end="")
    print(", This string should not break")

    addageyorn=input("Would you like to add X amount of years to your age, y or n:: ")

    if addageyorn==("y"):
        addage=input("How many years do you want to add to your age:: ")
        print("OK, so you want to add ",addage," years to your current age of ",age, sep="", end="")
        exeaddage = int(age) + int(addage)
        computed = str(exeaddage)
        print(", In ",addage," years you will be ",computed," years old, thanks for signing in.", sep="")
        time.sleep(5)
        exit()

    if addageyorn==("n"):
        print("Thanks for signing in")
        time.sleep(5)
        exit()

    elif addageyorn!=("y", "n"):
        print("Invalid Input")

PHP:

json

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

如前所述,从PHP传递数据有多种选择:

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

    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请求的成功回调试图访问返回数据的属性 name 。但是,返回的数据应该是一个对象数组,每个对象都有一个属性 name 。记录每个属性名称的一种方法是使用Array.forEach()并将数组中每个元素的名称发送到console.log()

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

请参阅this phpfiddle中的演示。