简体   繁体   中英

How to load data in breaks from Ajax call?

Guys I have an ajax call on my page, which is being called on scroll down event (lazy loading).

This is the whole call :

function callMoreData()
{ $.ajax( {
                    type: "GET",
                    url: "/api/values/getnotice",
                    dataType: "json",
                    crossDomain: true,
                    async: true,
                    cache: false,
                    success: function (data) {
                        updateData(data);
                    },
                    error: function (x, e) {
                        alert('problem while fetching records!');
                    } });}

function updateData(data) {
    updateData = function (data) { };
    $.each(data, function (index, value) {
        BindNotice(value);
    });
}

function BindNotice(values)
{
 ...appending some div here with values...
}

now this call is returning all the data and display it all at once on first scroll event. What I want to do is, load the data in sets of two. For example, each loop gets executed on index 0 and 1 at first scroll, then on second scroll index 2 and 3 gets processed and then so on. How would I do about doing as? I have a very limited experience with JS/AJAX...

EDIT : CODE FROM CUSTOM LIBRARY :

$(".mainwrap .innnerwrap").mCustomScrollbar({
    autoDraggerLength:true,
    autoHideScrollbar:true,
    scrollInertia:100,
    advanced:{
        updateOnBrowserResize: true,
        updateOnContentResize: true,
        autoScrollOnFocus: false
    },
     callbacks:{
            whileScrolling:function(){WhileScrolling();},
            onTotalScroll: function () {
            callMoreData();
        }

    }
});

WebApi CODE :

[WebMethod]
[HttpGet]
public List<Notice> GetNotice()
{
    string con = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    SqlConnection Connection = new SqlConnection(con);
    string Query = "uSP_GetAllNotice";
    SqlCommand cmd = new SqlCommand(Query, Connection);
    cmd.CommandType = CommandType.StoredProcedure;
    DataTable dt = new DataTable();
    Connection.Open();
    dt.Load(cmd.ExecuteReader());
    Connection.Close();
    List<Notice> objNoticeList = new List<Notice>();
    foreach (DataRow row in dt.Rows)
    {
        Notice objNotice = new Notice();
        objNotice.Subject = row["subject"].ToString();
        objNotice.Date = Convert.ToDateTime(row["IssueDate"]);
        objNotice.Department = row["Department"].ToString();
        objNotice.Body = row["Body"].ToString();
        objNotice.NoticeImage = row["NoticeImage"].ToString();
        objNotice.Icon = row["Icon"].ToString();
        objNoticeList.Add(objNotice);
    }
    return objNoticeList;
}

First of all, you have to make sure the server-side delivers only as mutch elements as you like, so that would be something like

[...]
type: "GET",
url: "/api/values/getnotice/" + start + '/' + amount,
dataType: "json",
[...]

start and amount have to be defined outside the function, in a higher scope, so it's available by the ajax function. While amount will be more or less constant, start can be calculated. One option would be, to increment it on the success function. Another solution can be, to count the divs you already appended to your DOM.

The result could be something like:

var amount = 2;
var start = 0;

function callMoreData(){ 
    $.ajax( {
        type: "GET",
        url: "/api/values/getnotice/" + start + '/' + amount,
        dataType: "json",
        crossDomain: true,
        async: true,
        cache: false,
        success: function (data) {
            updateData(data);
            start += amount;
        },
        error: function (x, e) {
            alert('problem while fetching records!');
        } 
    });
}

I recommend NOT to put it in the global namespace, but to put it in a own one.

Maybe you can use paging parameters to get your data in chunks of two items at a time. Let the server handle the work of figuring out how to break the response data into two items per page.

$.ajax({
    type: "POST",
    url: "/api/values/getnotice",
    data: {
        'PageSize': pageSize, 
        'Page': page
    },
    type: "GET",
    dataType: "json",
    crossDomain: true,
    async: true,
    cache: false,
    success: function (data) {
        updateData(data);
    },
    error: function (x, e) {
        alert('problem while fetching records!');
    } 
});

Make a global variable such as

Var time_scrolled = 0; //in the beginning

when you receive scrolldown event your indexes at each request will be (time_scrolled*2) and (time_scrolled*2+1) then you increase time_scrolled by 1 as time_scrolled++;

Hope this will solve your problem.

Edited: complete code

    Var times_scrolled = 0; //in the beginning
    Var global_data = [];

        function callMoreData()
        { $.ajax( {
                            type: "GET",
                            url: "/api/values/getnotice",
                            dataType: "json",
                            crossDomain: true,
                            async: true,
                            cache: false,
                            success: function (data) {
                                global_data = data;
                            },
                            error: function (x, e) {
                                alert('problem while fetching records!');
                            } });}

    callMoreData(); //fetch data at the time of loading since it won't miss at first scroll
    function updateData(){
       var initial = times_scrolled*2;

            var final = initial+1;
            for(var i=initial;i<data.length && i<=final;i++)
            {
                BindNotice(global_data[i]);
            }
            times_scrolled++;

    }

        function BindNotice(values)
        {
         ...appending some div here with values...
        }


// modify custom library code to:

$(".mainwrap .innnerwrap").mCustomScrollbar({
    autoDraggerLength:true,
    autoHideScrollbar:true,
    scrollInertia:100,
    advanced:{
        updateOnBrowserResize: true,
        updateOnContentResize: true,
        autoScrollOnFocus: false
    },
     callbacks:{
            whileScrolling:function(){WhileScrolling();},
            onTotalScroll: function () {
            updateData();
        }

    }
});

This is what I did to solve my problem. This is my ajax call

function callMoreData() {
                var RoleCodes = $('#hiddenRoleCode').val();
                $.ajax(
                    {
                        type: "GET",
                        url: "/api/alert/getalerts?RoleCode=" + RoleCodes + "&LastAlertDate=" + formattedDate,
                        dataType: "json",
                        crossDomain: true,
                        async: true,
                        cache: false,
                        success: function(data) {
                            $.each(data.data, function (index, value) {
                                update();
                                BindAlert(value);
                            });
                        },
                        error: function(x, e) {
                            alert('There seems to be some problem while fetching records!');
                        }

                    }
                );
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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