gpt4 book ai didi

javascript - 在 PHP 和 Ajax 中从数据库数据动态创建下拉列表

转载 作者:行者123 更新时间:2023-12-03 11:28:05 26 4
gpt4 key购买 nike

我正在尝试制作动态下拉列表,该下拉列表将由从数据库收集的数据填充。我一直在解析 PHP 文件发送的多维数组中的数据。我的代码:

HTML 文件的一部分(仅负责的 JavaScript(Ajax 函数))

function mentor() {
// 1. Create XHR instance - Start
var oblast = document.getElementById("oblast").value; //previous dropdown from which I need to create next one
document.getElementById("mentorr").innerHTML = ""; //emtpy the dropdown I need to create

instancee();
// 1. Create XHR instance - End

// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
var val = xhr.responseText;
alert(val); //just a check to see does it get correct data, and it get, everything is OK so far

var jsonData = JSON.parse(val);
var selectList = document.getElementById('mentorr'); //id of the dropdown I need to create

for (var i in jsonData) {
var option = document.createElement('option');
//$response[$i]['name'];
option.value = jsonData['id'][i];
option.text = jsonData['name'][i];
selectList.appendChild(option);
}
}
}
}

// 2. Define what to do when XHR feed you the response from the server - Start

// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'ajax.php');

xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("oblast=" + oblast);
}

ajax.php 文件的一部分,用于获取数据并发送到 HTML:

$queryData1 = mysql_query("SELECT * FROM profesori WHERE idprof = '$prof'");

while($result2 = mysql_fetch_array($queryData1)) {
$id=$result2['idprof'];
$profesor=$result2['ime']. " ".$result2['prezime'];

$data = array
(
'id' => array($id),
'name' => array($profesor)
);

echo json_encode($data);
}

alert(var) 代码行给出:

enter image description here

因此,数据被正确地从数据库中获取并发送到 HTML。但问题在于填充下拉菜单(解析数据)。控制台中的“意外 token {”行中出现错误

var jsonData = JSON.parse(val);

有人知道如何解决这个问题吗?

最佳答案

for (var i = 0; i < jsonData.length; i++) {
var option = document.createElement('option');
option.value = jsonData[i].id;
option.text = jsonData[i].name;
selectList.appendChild(option);
}

应该可以解决这个问题,JSON.parse 返回 json 对象,您可以使用索引循环遍历对象并获取对象的属性,如“object.property”。

关于javascript - 在 PHP 和 Ajax 中从数据库数据动态创建下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26840811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com