第一次使用AJAX,通过AJAX循环JSON以及多个页面上的数据?

时间:2014-06-24 00:48:06

标签: javascript jquery ajax json

第一次使用AJAX用户..我有15组数据,我希望用户一次引入。即:

{"status":"Success","message":"My contents","data":[
  {"Contents":{"id":"1","Type":"fb","profileId":"123456","profileName":"Test1","profileImage":"https:\/\/fbcdn-profile-a.akamaihd.net\/hprofile-ak-xfp1\/t1.0-1\/p50x50\/10337453_7117502132131244_84974578537125246499_t.jpg","postMessage":"Hello \u2022 Test \u2022 testing message \u2022"}},
  {"Contents":{"id":"2","Type":"fb","profileId":"1234567","profileName":"Test2","profileImage":"https:\/\/fbcdn-profile-a.akamaihd.net\/hprofile-ak-xfp1\/t1.0-1\/p50x50\/10347453_7117503245184844_8497457853733242234_t.jpg","postMessage":"Hello \u2022 Test \u2022 testing message \u2022"}}
]}

那些最初的15使用网址http://www.example.com/services/request/,之后用户可以按下"加载更多"然后从http://www.example.com/services/request/page2获得下一个15,"加载更多"再次点击并从http://www.example.com/services/request/page3等获取

我意识到我需要在这里做一些事情:
  - 在文档加载时,运行第一个ajax请求
  - 可能使用.stringify解析JSON,但在我下面的尝试中没有使用它,不确定是否需要?   - 添加"加载更多"因此当用户按下它时,它将从下一页获取数据,等等

对于数组中的每个对象,数据应作为div内的新container添加,即使用第一个对象:

<div id="container">
  <div class="fb"> <!--type as class-->
    <div class="name">Test1</div> <!--text from profileName-->
    <div class="image"><img src="https:\/\/fbcdn-profile-a.akamaihd.net\/hprofile-ak-xfp1\/t1.0-1\/p50x50\/10337453_7117502132131244_84974578537125246499_t.jpg" /></div><!--image url from profileImage-->
    <div class="message">Hello \u2022 Test \u2022 testing message \u2022</div><!--text from postMessage-->
  </div> <!--end of generated object-->
</div> <!--//container-->

我尝试加载文档(初始请求):

    $(function() { //document ready
        $.getJSON('http://www.example.com/services/request/', function(data) {
          $.each(data, function(index) {
          $('#container').append(
            $('<div class="'+data.type+'">'), 
            $('<div class="name">').html(data.profileName),
            $('<div class="image">').html("<img src='+data.profileImage+' < />"),
            $('<div class="message">').html(data.postMessage)
          )
        });
    });
});

好的,我将此附加到#container,但不正确..为什么?此外,&#34; undefined&#34;应该是fb类的div应该包围其下面的其他div。

<div class="undefined"></div>
<div class="name"></div>
<div class="image">
<img <="" src="+data.profileImage+">
</div>
<div class="message"></div>

3 个答案:

答案 0 :(得分:4)

两件事:把你已经在一个单独的函数中工作的请求,例如。 loadPage(因此您无需重写该功能)。有没有加载直接网址,但把它作为一个参数。

因此,在文档加载时,将page变量设置为1,然后使用该页面开始第一次运行。

添加“加载更多”按钮和按钮处理程序,它将调用loadPage并包含页面变量。

例如

$(document).ready(function() {
    // set this here so that it is kept in reach.
    var page = 2;

    // this will call the required url, assemble it as needed.
    function loadPage(page) {
        var url = 'http://www.example.com/services/request/' + page;
        $.getJSON(url, function(data) {
            $.each(data, function(index) {
                $('#container').append(<YOURDATAHERE>);
            });
          )
        }
    }

    // This is the Load More handler - attach it to the button.

    function loadMore() {
        loadPage('page' + page);
        page = page + 1;
    };

    // Now make the first, initial run with no 'page1' as in your example.
    loadPage('');
});

如果需要,您可以以类似的方式实现分页器。

答案 1 :(得分:3)

虽然@Zlatko已经覆盖了更多&#34;功能很好,这里是如何改进你的DOM代码,使其结构类似于你提供的示例标记:

var cont = $('#container');
$.each(data.data, function(index, obj) {
    var item = obj.Contents;
    cont.append(
      $('<div>', {"class": item.Type}).append(
        $('<div>', {"class":"name", text:item.profileName}),
        $('<div>', {"class":"image"}).append(
          $('<img>', {src:item.profileImage})
        ),
        $('<div>', {"class":"message", text:item.postMessage})
      )
    );
});

答案 2 :(得分:1)

第一关,不要使用每个回调数据。

在前端

,您可以使用JSON.parse(data)将数据导入对象。像这样

var records = data,
var length = records.data.Contents.length;//you seem to have overcomplicated your object structure for no reason.
for(var iterator = 0; iterator < length; iterator++)
{
    //now you can access your properties like so
    var Type = records.data.Contents[iterator].Type,
    var id   = records.data.Contents[iterator].id;//you can access properties of your objects as simple as this.
    if(Type == 'Fb')
    {
        //any properties unique to this type go here.
            //example
            var ProfileId = records.data.Contents[iterator].ProfileId;
        $('#somediv ul').append('<li target="'+id+'">'+Type+'<a href=?profile'+ProfileId+'</li>');
    }
    //so on and so forth for all your various Types
}

现在当用户需要加载更多

$('#load-morestuff').click(function(){
    var lastid = $(this).parents('ul > li:last-child').attr('target');//we get the id of the last result turned from  the ajax request(s)
    //you may have to play with this a bit in order to get the last child. i don't have reference on hand or time to test it, but i recall doing something
    //similar in a previous project.
    $.get('someurl&id='+lastid, function(data){
        //now you've sent the lastid. the serverside script should fetch startign from this last id. presto, you have jquery pagination.
        //now it is the same as the first example you append it to the divs. cool stuff eh?
    });
});