【发布时间】:2015-01-06 13:55:44
【问题描述】:
我正在尝试制作将由从数据库收集的数据填充的动态下拉列表。我被困在从 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。但问题在于填充下拉菜单(解析数据)。控制台中的“意外令牌 {”行中的错误
var jsonData = JSON.parse(val);
有谁知道如何解决这个问题?
【问题讨论】:
-
您可以调用 val.toString() 并检查它是否真的是 JSON。
-
JSON.parse('{"id":["2"],"name":["Zdravko Topic"]}')工作正常,尽管您不需要在 php 代码中转换array。 -
它真的是 JSON.. 我不能那样解析,因为值不会是 "id":["2"],"name":["Zdravko Topic"] 总是,问题是如何解析具有值的多维数组 ('id' => $varid, 'name'=> $varname) 并将其放入下拉列表中,例如
标签: javascript php ajax multidimensional-array