我一直试图让我的AJAX工作几天,我不明白为什么它不起作用。它没有提醒任何事情并给我一个错误:Failed to load resource: the server responded with a status of 404 (Not Found) - [object%20Object]
它也会一直返回NULL,JS,PHP。不知道为什么。
JS
var fullName = ["John Doe", "Jane Doe"];
$(window).load(function(){
getList();
});
function getList(){
$.getJSON({
type: "GET", /* the request's method: */
url:"/names.php", /* the request's location: */
data: JSON.stringify({names: fullName}), /* the request's fields: */
contentType: "application/json; charset=utf-8", /* the request's content-type : */
dataType:"json", /* the response's content-type: */
success: function(json){ /* the callback function */
if(json.length > 0){
$.each(json, function(i, v){
console.info(v);
});
}
else {
alert('wtf?!');
}
}
});
}
PHP
<?php
$req=array_merge($_GET, $_POST);
$names=json_decode($req['names'], true);
header('content-type: application/json; charset=utf8;');
echo json_encode($names);
答案 0 :(得分:4)
您应该使用$.ajax
代替getJSON
。 jQuery认为整个配置对象就是URL!
此外,当您将其更改为.ajax
时,您不必JSON.stringify
数据,这将自动完成。所以代码应该是:
function getList(){
$.ajax({
type: "GET", /* the request's method: */
url:"/names.php", /* the request's location: */
data: {names: fullName}, /* the request's fields: */
contentType: "application/json; charset=utf-8", /* the request's content-type : */
dataType:"json", /* the response's content-type: */
success: function(json){ /* the callback function */
if(json.length > 0){
$.each(json, function(i, v){
console.info(v);
});
} else {
alert('wtf?!');
}
}
});
}
使用getJSON的较短版本可能是:
function getList(){
$.getJSON("/names.php", {names: fullName}, function(json){
if(json.length > 0){
$.each(json, function(i, v){
console.info(v);
});
} else {
alert('wtf?!');
}
});
}
但是请求不会作为JSON发送(只有响应应该是JSON)。所以你需要对你的PHP稍作修改:
<?php
$names=$_GET['names'];
header('content-type: application/json; charset=utf8;');
echo json_encode($names);
答案 1 :(得分:0)
将代码中的.getJSON
更改为.ajax
,其余的应该可以提供URL中的路径是否正确。
答案 2 :(得分:0)
从jQuery docs开始,jQuery.getJSON是:
的缩写$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
所以你应该这样使用:
$.getJSON('/names.php', {names: fullName},
function(data) {...}
);