我已经尝试几天了,但是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);
You should be using $.ajax
instead of getJSON
. jQuery is thinking the whole configuration object is the URL!
Also, when you change it to .ajax
, you don't have to JSON.stringify
the data, that will be done automatically. So the code should be:
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?!');
}
}
});
}
A shorter version using with getJSON could be:
function getList(){
$.getJSON("/names.php", {names: fullName}, function(json){
if(json.length > 0){
$.each(json, function(i, v){
console.info(v);
});
} else {
alert('wtf?!');
}
});
}
But then the requests would not be sent as JSON (only the response is expected to be JSON). So you'd need a slight change on your PHP:
<?php
$names=$_GET['names'];
header('content-type: application/json; charset=utf8;');
echo json_encode($names);
change .getJSON
in your code to .ajax
and the rest shoud work provided the path in URL is corret.
From jQuery docs, jQuery.getJSON is a shorthand of:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
So you should use this way:
$.getJSON('/names.php', {names: fullName},
function(data) {...}
);