jQuery/Ajax-解析JSON响应 [英] Jquery/Ajax - Parse JSON Response

查看:117
本文介绍了jQuery/Ajax-解析JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 http://randomuser.me/documentation.html api.它只是生成json格式的随机用户数据.但是,我似乎无法解析响应.每当我做的时候,我都会得到未定义的对象.

I'm playing around with the http://randomuser.me/documentation.html api. It just generates random user data in json format. However, I can not seem to parse the response. Whenever I do, I just get undefined objects.

这是我的代码:

<script>
  $.ajax({
        url: 'http://api.randomuser.me/',
        dataType: 'json',
        success: function (data) {
            console.log(data);
            alert(data.user);
        }
    });
</script>

<div id="user"></div>

推荐答案

仔细看一下返回的JSON.您正在获取正确解码的数据,但是数据结构与您期望的数据不匹配.

Take a good look at the JSON being returned. You are getting the properly-decoded data, but the data structure does not match what you are expecting.

user字段位于名为results的数组中,您必须使用索引对其进行访问.例如,要获得第一个用户:

The user field is inside of an array called results which you have to access with an index. For example, to get the first user:

var user = data.results[0].user;

如果您要请求多个结果,也可以使用循环结构.

You can also use a loop structure if you are requesting multiple results.

这篇关于jQuery/Ajax-解析JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆