第一次使用AJAX时,JSON通过AJAX循环处理多个页面上的数据

First time using AJAX, JSON loop via AJAX with data on several pages?

本文关键字:AJAX 数据 处理 循环 通过 JSON 第一次      更新时间:2023-09-26

第一次使用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使用url http://www.example.com/services/request/,之后用户可以按"加载更多",然后从http://www.example.com/services/request/page2中获得下一个15,再次点击"加载更多",从http://www.example.com/services/request/page3中获得。

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

对于数组中的每个对象,数据应该作为新的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,但不正确…为什么?此外,"undefined"div应该是fb类,应该环绕它下面的其他div。

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

两件事:将您已经在工作的请求放在一个单独的函数中,例如;loadPage(所以你不需要重写函数)。让它不直接加载url,而是把它作为一个参数。

因此,在文档加载时,将page变量设置为1,并从该页开始第一次运行。

添加"Load more"按钮和按钮处理程序,该按钮处理程序将调用loadPage并包含page变量。

$(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('');
});

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

虽然@Zlatko已经很好地涵盖了"load more"功能,但这里是如何改进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})
      )
    );
});

首先,不要使用data的回调。

在前端的

中,您可以使用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?
    });
});