我正在尝试使用JSON从JavaScript中的PHP文档接收数组。 PHP文档发送数组(当我用浏览器打开PHP文件时打印它)但不调用success()
或done()
方法。我在这里做错了什么?
代码:
的JavaScript :
function updateHighscores() {
//var functionName = "showData";
$.ajax({
//type: "GET",
dataType: "json",
url: "gesallprov.php",
//data: {functionName: functionName},
}).done(function(data) {
window.alert("GGGG");
var table = "<table style='width:100%'>" +
"<tr>" +
"<th>No.</th>" +
"<th>Name</th>" +
"<th>Date & Time</th>" +
"<th>Score</th>" +
"</tr>";
$(data).each(function(index, value) {
var i = 1;
table += "<tr>" +
"<td>" + i + "</td>" +
"<td>" + value.name + "</td>" +
"<td>" + value.when + "</td>" +
"<td>" + value.score + "</td>" +
"</tr>";
i++;
});
}
PHP :
function showData() {
try {
$dbh = new PDO(...);
$st = $dbh->prepare("SELECT `name` , `when` , `score` FROM `snake` ORDER BY `score` DESC");
$st->execute();
$result = $st->fetchAll(PDO::FETCH_ASSOC);
return $result;
$st = null;
$dbh = null;
}
catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
}
echo json_encode(showData());
答案 0 :(得分:0)
如果我测试您的代码,我会在浏览器控制台中看到此消息:
参数列表之后SyntaxError:missing)
如果你在updateHighscores
函数中添加右括号和大括号,它可能会有所帮助:
function updateHighscores() {
//var functionName = "showData";
$.ajax({
//type: "GET",
dataType: "json",
url: "gesallprov.php",
//data: {functionName: functionName},
}).done(function (data) {
window.alert("GGGG");
var table = "<table style='width:100%'>" +
"<tr>" +
"<th>No.</th>" +
"<th>Name</th>" +
"<th>Date & Time</th>" +
"<th>Score</th>" +
"</tr>";
$(data).each(function (index, value) {
var i = 1;
table += "<tr>" +
"<td>" + i + "</td>" +
"<td>" + value.name + "</td>" +
"<td>" + value.when + "</td>" +
"<td>" + value.score + "</td>" +
"</tr>";
i++;
});
});
}
答案 1 :(得分:0)
为什么不尝试以下代码,它可以帮助您解决问题
jQuery.ajax({
type: "POST",
url: "gesallprov.php",///contain the url of ajax
// data:formData,
dataType:"json",
success : function (data)
{
window.alert("GGGG");
var table = "<table style='width:100%'>" +
"<tr>" +
"<th>No.</th>" +
"<th>Name</th>" +
"<th>Date & Time</th>" +
"<th>Score</th>" +
"</tr>";
$(data).each(function(index, value) {
var i = 1;
table += "<tr>" +
"<td>" + i + "</td>" +
"<td>" + value.name + "</td>" +
"<td>" + value.when + "</td>" +
"<td>" + value.score + "</td>" +
"</tr>";
i++;
});
},
error :function(xhr, ajaxOptions, thrownError){
console.log(xhr);
console.log(ajaxOptions);
// console.log(thrownError);
//alert(xhr.status);
//alert(ajaxOptions);
}
})