如何使用 jQuery/JavaScript 解析 JSON 数据? [英] How to parse JSON data with jQuery / JavaScript?
问题描述
我有一个 AJAX 调用,它返回一些像这样的 JSON:
$(document).ready(function () {$.ajax({类型:'获取',url: 'http://example/functions.php',数据:{ get_param: '值' },成功:功能(数据){变量名 = 数据$('#cand').html(数据);}});});
在 #cand
div 里面我会得到:
[ { "id" : "1", "name" : "test1" },{ "id" : "2", "name" : "test2" },{ "id" : "3", "name" : "test3" },{ "id" : "4", "name" : "test4" },{id":5",名称":test5"}]
如何遍历这些数据并将每个名称放在一个 div 中?
假设您的服务器端脚本没有设置正确的 Content-Type: application/json
响应标头,您需要指出jQuery 通过使用 dataType: 'json'
参数确定这是 JSON.
然后你可以使用 $.each()
函数来循环数据:
$.ajax({类型:'获取',url: 'http://example/functions.php',数据:{ get_param: '值' },数据类型:'json',成功:功能(数据){$.each(data, function(index, element) {$('body').append($('', {文本: element.name}));});}});或使用 $.getJSON
方法:
$.getJSON('/functions.php', { get_param: 'value' }, function(data) {$.each(data, function(index, element) {$('body').append($('', {文本: element.name}));});});I have a AJAX call that returns some JSON like this:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://example/functions.php',
data: { get_param: 'value' },
success: function (data) {
var names = data
$('#cand').html(data);
}
});
});
Inside the #cand
div I'll get:
[ { "id" : "1", "name" : "test1" },
{ "id" : "2", "name" : "test2" },
{ "id" : "3", "name" : "test3" },
{ "id" : "4", "name" : "test4" },
{ "id" : "5", "name" : "test5" } ]
How can I loop through this data and place each name in a div?
解决方案 Assuming your server side script doesn't set the proper Content-Type: application/json
response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json'
parameter.
Then you could use the $.each()
function to loop through the data:
$.ajax({
type: 'GET',
url: 'http://example/functions.php',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
}
});
or use the $.getJSON
method:
$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
});
这篇关于如何使用 jQuery/JavaScript 解析 JSON 数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文