gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:10:36 24 4
gpt4 key购买 nike

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

关于javascript - 使用 json_encode() 将 PHP 数组转换为 JavaScript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44350982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com