如何在javascript中显示json对象数组的特定值?
问题描述:
我对ajax对象的显示值有些怀疑。我需要通过使用ajax在选择框中显示名称。我不知道我犯了什么错误,我可以更改我的代码。请帮助我的任何人。提前感谢您。如何在javascript中显示json对象数组的特定值?
我的JavaScript代码:
function getClient() {
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var message = xmlhttp.responseText;
var client = JSON.parse(message);
console.log(Object.keys(client));
document.forms["project_form"]["Project_cid"].innerHTML='<select class="form-control" maxlength="100" name="Project[cid]" id="Project_cid"><option value=Select>'+Object.keys(client)+'</option></select>'
}
}
var url = "/pms_pro/index.php/client/list";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(null);
}
当我使用警报(消息),它会显示如下图所示,
[{"cid":"1","name":"suresh","address":"Chennai"},{"cid":"2","name":"Ramesh","address":"Namakkal"},{"cid":"3","name":"Vignesh","address":"Trichy"}]
答
事情是这样的:
var select = document.getElementById('Project_cid');
// remove existing options
select.innerHTML = '';
// add the new options
var option, i;
for (i = 0; i < client.length; i++) {
option = document.createElement('option');
option.text = client[i].name;
option.value = client[i].cid;
select.add(option);
}
谢谢伊利亚·霍利..我明白了 – 2014-09-13 08:03:19