Javascript(Ajax)解析JSON值
这里没有人。只是试着理解这门语言 我使用以下代码请求JSON请求:Javascript(Ajax)解析JSON值,javascript,jquery,json,ajax,Javascript,Jquery,Json,Ajax,这里没有人。只是试着理解这门语言 我使用以下代码请求JSON请求: function request(){ $.ajax({ dataType: "jsonp", type: 'GET', url: "getWebsite", success: function(result){ data = result; $('.data').text(data); console.log
function request(){
$.ajax({
dataType: "jsonp",
type: 'GET',
url: "getWebsite",
success: function(result){
data = result;
$('.data').text(data);
console.log(data);
}});
get请求返回如下内容:
"items": [
{
"topLevelComment": {
"authorDisplayName": "a"
"textDisplay": "b"
},
{
"topLevelComment": {
"authorDisplayName": "c"
"textDisplay": "d"
}
我想循环查看AuthorDisplayName和textDisplay,并从中随机选择一个。如果我不得不猜测的话,最好的方法可能是将它们都放入数组中。我甚至不知道该怎么做。项目已经是一个数组了。因此,您可以执行以下操作:
仅当返回字符串时才将结果解析为json
items=JSON.parseitems
获取一个随机索引
让index=Math.floorMath.random*items.length
获取随机数据
让authorDisplayName=items[index].topLevelComment.authorDisplayName
let textDisplay=items[index].topLevelComment.textDisplay
据我所知,您试图显示items数组中的随机对象 items变量已经是一个数组,因此不需要创建数组。要获取数组的随机元素,可以使用以下代码:
function request(){
$.ajax({
dataType: "jsonp",
type: 'GET',
url: "getWebsite",
success: function(result){
data = result;
$('.data').text(data);
console.log(data);
}});
var item=result.items[Math.floorMath.random*items.length]
我不确定items数组的确切位置,假设它位于结果的根上。您可能还需要通过JSON.parse方法运行该数组,使其成为有效的JavaScript对象
然后,要获取文本和显示名称,可以执行以下操作:
var authour=item.topLevelComment.authorDisplayName;
var text=item.topLevelComment.textDisplay;
var-json={
项目:[{
topLevelComment:{
authorDisplayName:a,
文本显示:b
}
}, {
topLevelComment:{
authorDisplayName:c,
文本显示:d
}
}, {
topLevelComment:{
authorDisplayName:e,
文本显示:f
}
}, {
topLevelComment:{
authorDisplayName:g,
文本显示:h
}
}]
};
$input:button.onclick,函数{
selectRand=Math.floorMath.random*json.items.length
var r=json.items[selectRand].topLevelComment.textDisplay;
console.logr;
};
如果您的数据已经是对象格式,并且您只希望从随机拾取中获取一个。这样,就不必对所有数据进行循环。只需从总数据中随机选择一个索引即可
function request(){
$.ajax({
dataType: "jsonp",
type: 'GET',
url: "getWebsite",
success: function(result){
data = result;
$('.data').text(data);
console.log(data);
var randomIndex = Math.floor((Math.random() * data.items.length));
console.log("Selected data authorDisplayName: " + data.items[randomIndex].topLevelComment.authorDisplayName);
console.log("Selected data textDisplay: " + data.items[randomIndex].topLevelComment.textDisplay);
}
});
}
结果已经是对象格式还是仍然是JSON字符串格式?你能试着做console.logtypeofdata@VikiTheolorado对象格式,您从每个对象中随机选择一个是什么意思。你的意思是在所有数组中显示authorDisplayName和textDisplay中的一个,还是在每个注释的authorDisplayName和textDisplay之间显示?@VikiTheolorado基本上JSON请求有100多个authorDisplayName和100多个textDisplay。我想循环所有的值,然后随机选择一个用于AuthorDisplayName,一个用于textDisplay。请求的结果存储在变量“data”中。返回无法读取未定义的属性“authorDisplayName”