获取Json对象并使用Jquery在页面上显示它们

时间:2012-01-09 20:25:19

标签: jquery json

我有一个动态网址(http://domain.com/getUsers.php?team=1),如果手动访问它,会在浏览器上返回一些Json对象:

[{"id":1,"name":"George"},{"id":2,"name":"John"}]

*我没有访问getUsers.php所以,我无法编辑此文件。 *如果我在浏览器上查看此文件的源代码,我只会获得纯json对象而没有任何其他HTML相关标签,如标题,正文等。

我想将所有json元素显示在其他页面的下拉菜单中(http://domain.com/index.html)。

<form>
<select name="users">
<option value="">Select a person:</option>
<option value="1">George</option>
<option value="2">John</option>

</select>
</form>

使用Jquery执行此操作的最佳方法是什么? 我需要在index.html页面上放置什么Jquery代码来检索和显示数据?

谢谢你!

1 个答案:

答案 0 :(得分:3)

基本上,诀窍是迭代你收到的JSON对象并用它创建元素。

这是一个如何做到这一点的例子(这里是一个小提琴:http://jsfiddle.net/ruv3M/

    // This is to simulate the JSON you retrieved via an AJAX call
var people = [{"id":1,"name":"George"},{"id":2,"name":"John"}],
    // Save a reference to your list of users
    $userSelect = $( '#userlist' ).find( 'select' );

// Iterate over each item in the object of people you received
for ( person in people ) {
    // create an option for each person
    $( '<option />', {
        value: people[person].id,
        text: people[person].name
    })
        // Append it to your list
        .appendTo( $userSelect ); 
}

更新:对JSON数据进行AJAX调用的最简单方法是使用$.getJSON()。 (Documentation

在您的代码中,它可能看起来像这样:

// Instead of '/echo/json/', you'd use your AJAX URL
$.getJSON( '/echo/json/', function( data ) {
    // Set data equal to our dummy people variable, since it's blank in this example
    // NOTE! This step would be unnecessary in real life, where data would already be your JSON
    data = people;

    // Iterate over each item in the object of people you received
    // Note: iteration should be inside this callback, so it doesn't fire till your
    // data has been returned.
    for ( person in people ) {
        // create an option for each person
        $( '<option />', {
            value: people[person].id,
            text: people[person].name
        })
            // Append it to your list
            .appendTo( $userSelect ); 
    }

});

http://jsfiddle.net/B2YF5/3/