如何使用jquery在html中使用json数据

时间:2016-08-25 12:25:06

标签: jquery json

这是json数据来自php

[{"employee_id":"1","first_name":"Ganesh","last_name":"Mulay"},
 {"employee_id":"2","first_name":"khalid","last_name":"shaikh"},
 {"employee_id":"3","first_name":"Navnath","last_name":"Bangar"}
]

我想要这样的输出

<option value="1"> Ganesh Mulay </option>
<option value="2"> khalid shaikh </option>
<option value="3"> Navnath Bangar</option>

3 个答案:

答案 0 :(得分:0)

与使用javascript

相同

for (var i = 0; i < arr.length; i++) // Do something like arr[i].employee_id;

请检查此示例:https://jsfiddle.net/14ra68hs/

答案 1 :(得分:0)

var jData = [{
  "employee_id": "1",
  "first_name": "Ganesh",
  "last_name": "Mulay"
}, {
  "employee_id": "2",
  "first_name": "Rahul",
  "last_name": "kumar"
}, {
  "employee_id": "3",
  "first_name": "Kiran",
  "last_name": "Raj"
}];

$('<select id="test">').appendTo('body');
$.each(jData, function(index, value) {
  $('<option>').val(value.employee_id).text(value.first_name + ' ' + value.last_name).appendTo('select#test');
});

&#13;
&#13;
var jData = [{
  "employee_id": "1",
  "first_name": "Ganesh",
  "last_name": "Mulay"
}, {
  "employee_id": "2",
  "first_name": "Rahul",
  "last_name": "kumar"
}, {
  "employee_id": "3",
  "first_name": "Kiran",
  "last_name": "Raj"
}];

$('<select id="test">').appendTo('body');
$.each(jData, function(index, value) {
  $('<option>').val(value.employee_id).text(value.first_name + ' ' + value.last_name).appendTo('select#test');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

  

JS Fiddle

答案 2 :(得分:0)

你可以做这样的事情

&#13;
&#13;
$(document).ready(function(){

var json =[{"employee_id":"1","first_name":"Ganesh","last_name":"Mulay"},{"employee_id":"2","first_name":"Rahul","last_name":"kumar"},{"employee_id":"3","first_name":"Kiran","last_name":"Raj"}
];


//convert json to object


var html = "";

for(var key in json)
{
  
  html += '<option value="'+json[key].employee_id+'">'+
json[key].first_name+ ' '+json[key].last_name+'</option>';

}
  
 $("select").html(html)

})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select>

</select>
&#13;
&#13;
&#13;