繁体   English   中英

Javascript(Ajax)解析JSON值

[英]Javascript (Ajax) Parse JSON value

总的JavaScript新手在这里。 只是想对语言有所了解。

我正在使用以下代码请求JSON请求:

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并从中随机选择一个。 最好的方法可能是将它们都放入数组(如果我不得不猜测的话)。 我不确定该如何解决。

 var json={ "items": [{ "topLevelComment": { "authorDisplayName": "a", "textDisplay": "b" } }, { "topLevelComment": { "authorDisplayName": "c", "textDisplay": "d" } }, { "topLevelComment": { "authorDisplayName": "e", "textDisplay": "f" } }, { "topLevelComment": { "authorDisplayName": "g", "textDisplay": "h" } }] }; $("input:button").on("click",function(){ selectRand = Math.floor((Math.random() * json.items.length)) var r=json.items[selectRand].topLevelComment.textDisplay; console.log(r); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="button" value="selectRand"/> 

items已经是一个数组。 因此,您需要执行以下操作:

  1. 将结果解析为json(仅当返回字符串时)

    items = JSON.parse(items)

  2. 获取随机索引

    let index = Math.floor((Math.random() * items.length))

  3. 获取随机数据

    let authorDisplayName = items[index].topLevelComment.authorDisplayName
    let textDisplay = items[index].topLevelComment.textDisplay

据我了解,您正在尝试从items数组中显示一个随机对象?

items变量已经是一个数组,因此您无需创建一个数组。 要获得数组的随机元素,可以使用以下代码:

var item = result.items[Math.floor(Math.random()*items.length)];

我不确定items数组的确切位置,可以说它位于结果的根上。 您可能还需要通过JSON.parse()方法运行数组,以使其成为有效的JavaScript对象。

然后,要获取文本和显示名称,可以执行以下操作:

var authour = item.topLevelComment.authorDisplayName; var text = item.topLevelComment.textDisplay;


如果您的数据已经是对象格式,并且您只想从随机选择中获取一个即可。 然后,您不必循环所有数据。 只需从总数据中随机选择一个索引即可。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM