2014-09-13 102 views
-1

我對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"}] 

回答

0

事情是這樣的:

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); 
} 
+0

謝謝伊利亞·霍利..我明白了 – 2014-09-13 08:03:19

相關問題