Javascript 使用PDO查询作为可选择选项构建选择列表
我想创建一个选择列表,列出查询中的项目/信息。每次我更新数据库时都需要更新选择列表,所以我必须使用JQuery。我从未使用过JSON,所以我真的很糟糕,也没有经验 我想输出“选择”列表中每个选项的“电子邮件”和“余额”字段,如下所示:Javascript 使用PDO查询作为可选择选项构建选择列表,javascript,php,jquery,json,pdo,Javascript,Php,Jquery,Json,Pdo,我想创建一个选择列表,列出查询中的项目/信息。每次我更新数据库时都需要更新选择列表,所以我必须使用JQuery。我从未使用过JSON,所以我真的很糟糕,也没有经验 我想输出“选择”列表中每个选项的“电子邮件”和“余额”字段,如下所示: <option>john@doe.com - 120020</option> <option>john2@doe.com - 130020</option> 我的数据库/accounts.php 我的问题是: 我不
<option>john@doe.com - 120020</option>
<option>john2@doe.com - 130020</option>
我的数据库/accounts.php
我的问题是:
我不知道如何以这种方式实现Ajax请求,它循环遍历所有行,并将必要的字段作为选项添加到select字段中。首先,因为您显式地放置了dataType:json,所以不需要json.parse 其次,只需在收到服务器的响应后构建标记: 粗略的例子:
$.ajax({
url: "/database/accounts.php",
type: "GET",
success: function (response) {
var opt = '';
// loop the response
$.each(response, function(i, e){
// just use your column names, these are just an example, but you get the idea
opt += '<option value="'+e.id+'">'+e.email+'</option>';
});
// append the markup to that select box
$('select#whatever_this_selectbox_is').html(opt);
},
dataType: "json"
});
旁注:我建议使用$result=$stmt->fetchAllPDO::FETCH_ASSOC;,因为您确实不需要在数字索引中输入值。旁注-使用dataType:json或var data=json.parseresponse;,不是两个都需要。所以您只需要获得成功响应的帮助:函数响应并将其添加到?没错,只要database/accounts.php也可以。感谢您的旁注,更改了。只需创建一个ajax请求,该请求还将发送您在选择框中选择的请求,该请求还必须包含在requestGhost中。我希望通过上面的SQL查询选择的信息填充此选择列表。我想你误解了我的问题。致命错误:未定义的类常量“FETCH\u ALL”
function buildSelectList(){
$.ajax({
url: "/database/accounts.php",
type: "GET",
success: function (response) {
var data = JSON.parse(response);
alert(data.id);
},
dataType: "json"
});
}
function selectPlayerless(PDO $db){
$stmt = $db->prepare("SELECT * FROM Accounts WHERE id NOT IN (SELECT accountId FROM PlayerCards)");
$stmt->execute();
$result = $stmt->fetchAll();
echo json_encode($result);
}
$.ajax({
url: "/database/accounts.php",
type: "GET",
success: function (response) {
var opt = '';
// loop the response
$.each(response, function(i, e){
// just use your column names, these are just an example, but you get the idea
opt += '<option value="'+e.id+'">'+e.email+'</option>';
});
// append the markup to that select box
$('select#whatever_this_selectbox_is').html(opt);
},
dataType: "json"
});