javascript 如何在 $.ajax 响应中从 JSON 中提取数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18759981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extract Array from JSON in $.ajax response
提问by Ganesh Babu
I have a json value converted from array in ajax response.
我有一个从 ajax 响应中的数组转换的 json 值。
{"Text":"Please provide a value","Email":"Please provide a value"}
I need the response json to be extracted in a div using $(div).html():
我需要使用 $(div).html() 在 div 中提取响应 json:
Text-Please provide a value
Email-Please provide a value
I tried it using $.each():
我用 $.each() 试过了:
var json=JSON.stringify({"Text":"Please provide a value","Email":"Please provide a value"});
var arr = [];
var obj = jQuery.parseJSON(json);
$.each(json,function(key,value)
{
arr.push('<li>'+value+'</li>');
});
var arrval =arr.join('');
console.log(arrval);
But I got output as undefined. I know there is some logical mistake I have done while extracting? What have I done wrong in here??
但是我得到的输出是未定义的。我知道我在提取时犯了一些逻辑错误?我在这里做错了什么??
Note: The array key value pair in json can be dynamic ie., it may be one, two or more..
注意:json 中的数组键值对可以是动态的,即可以是一个、两个或多个..
回答by asharajay
see this if it helps !!
看看这个如果有帮助!!
var jsonData = {"Text":"Please provide a value","Email":"Please provide a value"};
var arr = [];
for(var j in jsonData){
var sub_key = j;
var sub_val = eval("jsonData."+j);
arr.push('<li>'+sub_key+": "+sub_val+'</li>');
}
回答by user2660730
I think this might be helpful
我认为这可能会有所帮助
var json = {"Text":"Please provide a value","Email":"Please provide a value"};
var arr = [];
$.each(json,function(key,value){
arr.push('<li>'+value+'</li>');
});
var arrval =arr.join('');
console.log(arrval);
回答by Dawit
json is an array of objects, thus has a length property that you can use to iterate its elements.
json 是一个对象数组,因此有一个 length 属性,您可以使用它来迭代其元素。
var result;
for(var i=0;i<json.data.length;i++)
{
result += json.data[i].text+ ', ';
}
Most debugger consoles support displaying objects directly. Just check your result using
大多数调试器控制台支持直接显示对象。只需使用
console.log(obj);
回答by Hymany Lormoz
$(obj).each(function(index,value)
{
arr.push('<li>'+value.Text+'</li>');
});
your json have to look like:
你的 json 必须看起来像:
[{"Text":"Please provide a value","Email":"Please provide a value"}]