我正在尝试使用从数据库收集的数据来填充动态下拉列表。我坚持解析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);
}
获取数据并发送到HTML的ajax.php文件的一部分:
$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)
代码行给出了这个:
因此,可以从数据库中正确获取数据并将其发送到HTML。但问题在于填充下拉菜单(解析数据)。控制台出现错误&#34;意外令牌{&#34;在行
var jsonData = JSON.parse(val);
有谁知道如何解决这个问题?
答案 0 :(得分:1)
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对象,你可以使用索引循环访问对象并获取像这样的对象的属性&#34; object.property&#34;。