如何接收 JSON 数组
How do I receive JSON array?
我正在尝试使用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());
你为什么不尝试以下代码,它可能会帮助你解决问题
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);
}
})
如果我测试您的代码,我会在浏览器控制台中看到以下消息:
语法错误:参数列表后缺少 )
如果您在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++;
});
});
}
相关文章:
- 为DataTables aoColumnDefs创建JavaScript数组(JSON格式)
- 使用 Javascript 将行添加到数组 json
- PHP数组JSON编码和该对象在ExtJs中解码
- 数组json转换为数组json
- 将Blob文本转换为Javascript中的数组/JSON对象
- 如何合并这些数组/json 对象
- 尝试从数组 JSON 键中删除引号
- JavaScript 中的数组 JSON
- 在数组 JSON 格式的 JavaScript 变量末尾添加新地址
- 如何访问这个Javascript数组(JSON对象?)
- rails传递记录数组(JSON)
- 按值提取对象/数组json vs数组
- 获取具有子数组json值的数组的值
- Object对象数组Json.字符串数组的字符串化
- 如何在Ext js 4.1中过滤数组json
- PHP -多维数组Json
- 正在分析数组Json以选择Tag
- 试图将字符串数据转换为数值数据,将数据放入数组的数组(Json)
- 从数组json、javascript中的specf值中删除引号
- 使用JavaScript或jQuery读取数组JSON