json_encode返回空php数组
我想发送一个php数组到ajax,但它不起作用。说实话,我不知道我做错了什么。json_encode返回空php数组
我正在使用json_encode(),它返回null。
我的PHP代码:
$info = array();
$info['NEW YORK CITY'] = array(
'Name' => 'New York City'
);
$city = $_POST['city'];
if (strtoupper($city) === 'NEW YORK CITY') {
echo "Name: " . json_encode($info['NEW YORK CITY']['Name']) . ".<br>";
} else {
echo "error.";
}
我的Ajax代码:
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
//console.log(data);
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
//console.log(response);
$('form.ajax').html(response);
}
}).fail(function(jqXHR) {
alert(jqXHR.statusText);
});
return false;
});
定了!我有数组之前的json_encode。它现在起作用,我把数组放在最上面。
json_encode接受一个数组作为参数
,使得其将采取以下
array('key' => 'value')
这将被发送作为适当格式化JSON键:值。但是单个值无法正确处理,可能会导致不需要的结果。
json_encode的第一个参数不限于数组。字符串或数字是完全可以接受的输入。 – curtis1000
虽然是正确的,但要跟上实践要更直截了当,并且通常是建议的。虽然我的错误。 给提问用户或任何其他观众。这里是json_encode() 的文档链接http://php.net/manual/en/function.json-encode.php –
具有以下
$city = $_POST['city'];
if (strtoupper($city) === 'NEW YORK CITY') {
echo json_encode($info['NEW YORK CITY']);
} else {
echo json_encode(array("error."));
}
我得到一个内部服务器错误。 –
取代你的PHP代码试试这个,如果这个工程:
$city = $_POST['city'];
if (strtoupper($city) === 'NEW YORK CITY') {
echo json_encode(['Name' => $info['NEW YORK CITY']['Name'] ]);
} else {
echo json_encode(['error']);
}
阿贾克斯:
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
//console.log(response);
$('form.ajax').html(response);
}
}).fail(function(jqXHR) {
alert(jqXHR.statusText);
});
return false;
});
});
你阿贾克斯后应在上然后提交将触发AJAX功能。
我可以看到'print_r($ info);'? – aldrin27
$ info = array(); $ info ['纽约市'] = array('Name'=>'纽约市','Rank'=>'1st,US','Population'=>'8,991,079'); –