我试图发送一个php数组ajax,但它不工作。老实说,我不知道我做错了什么。
我使用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 key:value发送。但是单个值不能正确处理,可能会导致不想要的结果。
用下面的
替换PHP代码$city = $_POST['city'];
if (strtoupper($city) === 'NEW YORK CITY') {
echo json_encode($info['NEW YORK CITY']);
} else {
echo json_encode(array("error."));
}
如果可以的话试试这个:
$city = $_POST['city'];
if (strtoupper($city) === 'NEW YORK CITY') {
echo json_encode(['Name' => $info['NEW YORK CITY']['Name'] ]);
} else {
echo json_encode(['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;
$.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应该在on提交之后,然后它将触发ajax函数。