简体   繁体   English

如何从Ajax调用中临时加载数据?

[英]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). 伙计们,我的页面上有一个ajax调用,在向下滚动事件(延迟加载)中被调用。

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. 例如,每个循环在第一次滚动时在索引0和1上执行,然后在第二次滚动时对索引2和3进行处理,依此类推。 How would I do about doing as? 我该怎么做? I have a very limited experience with JS/AJAX... 我对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 : WebApi代码:

[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 首先,您必须确保服务器端仅按您希望的方式提供mutch元素,因此这类似于

[...]
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. 必须在更大的范围内在函数外部定义start和amount,因此ajax函数可以使用它。 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. 另一个解决方案是,计算已经附加到DOM的div。

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++; 当您收到(time_scrolled*2)事件时,每个请求的索引将是(time_scrolled*2)(time_scrolled*2+1)那么您将time_scrolled增加1,即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 这是我的ajax电话

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

                    }
                );
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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