Javascript 如何从Ajax调用中加载数据?
伙计们,我的页面上有一个ajax调用,它是在向下滚动事件(延迟加载)中调用的 这就是整个电话:Javascript 如何从Ajax调用中加载数据?,javascript,jquery,ajax,Javascript,Jquery,Ajax,伙计们,我的页面上有一个ajax调用,它是在向下滚动事件(延迟加载)中调用的 这就是整个电话: function callMoreData() { $.ajax( { type: "GET", url: "/api/values/getnotice", dataType: "json", crossDomain: true,
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...
}
现在,此调用将返回所有数据,并在第一个滚动事件中一次显示所有数据。我要做的是,以两个为一组加载数据。例如,每个循环在第一次滚动时在索引0和1上执行,然后在第二次滚动时处理索引2和3,依此类推。我该怎么做呢?我在JS/AJAX方面的经验非常有限
编辑:来自自定义库的代码:
$(".mainwrap .innnerwrap").mCustomScrollbar({
autoDraggerLength:true,
autoHideScrollbar:true,
scrollInertia:100,
advanced:{
updateOnBrowserResize: true,
updateOnContentResize: true,
autoScrollOnFocus: false
},
callbacks:{
whileScrolling:function(){WhileScrolling();},
onTotalScroll: function () {
callMoreData();
}
}
});
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;
}
[WebMethod]
[HttpGet]
公开名单公告()
{
string con=ConfigurationManager.ConnectionString[“conn”].ConnectionString;
SqlConnection=newsqlconnection(con);
字符串Query=“uSP\u GetAllNotice”;
SqlCommand cmd=新的SqlCommand(查询、连接);
cmd.CommandType=CommandType.storedProcess;
DataTable dt=新的DataTable();
Connection.Open();
dt.Load(cmd.ExecuteReader());
Connection.Close();
List objNoticeList=新列表();
foreach(数据行中的数据行)
{
通知对象=新通知();
objNotice.Subject=行[“Subject”].ToString();
objNotice.Date=Convert.ToDateTime(行[“IssueDate”]);
objNotice.Department=行[“Department”].ToString();
objNotice.Body=行[“Body”].ToString();
objNotice.NoticeImage=行[“NoticeImage”].ToString();
objNotice.Icon=行[“Icon”].ToString();
添加(objNotice);
}
返回objNoticeList;
}
首先,您必须确保服务器端只提供您喜欢的多个元素,因此
[...]
type: "GET",
url: "/api/values/getnotice/" + start + '/' + amount,
dataType: "json",
[...]
start和amount必须在函数之外的更高范围内定义,因此它可以由ajax函数使用。虽然数量或多或少是恒定的,但可以计算起始值。
一个选项是,在success函数上增加它。
另一个解决方案是,计算已经附加到DOM中的div
结果可能是:
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!');
}
});
}
我建议不要将它放在全局名称空间中,而是放在自己的名称空间中。也许您可以使用分页参数一次将数据分为两个项。让服务器处理如何将响应数据拆分为每页两项的工作
$.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!');
}
});
生成一个全局变量,例如
Var time_scrolled = 0; //in the beginning
当您收到scrolldown事件时,每个请求的索引将是(time\u scrolled*2)
和(time\u scrolled*2+1)
,然后您将time\u scrolled增加1作为time\u scrolled++代码>
希望这能解决你的问题
编辑:
完整代码
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();
}
}
});
Var times\u scrolled=0//一开始
Var全局_数据=[];
函数callMoreData()
{$.ajax({
键入:“获取”,
url:“/api/values/getnotice”,
数据类型:“json”,
跨域:是的,
async:true,
cache:false,
成功:功能(数据){
全局数据=数据;
},
错误:函数(x,e){
警报(“获取记录时出现问题!”);
} });}
callMoreData()//在加载时获取数据,因为它不会在第一次滚动时丢失
函数updateData(){
var initial=滚动次数*2;
var final=初始值+1;
对于(var i=initial;i这就是我解决问题所做的。这是我的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!');
}
}
);
}
我不明白..我的webapi url不包含start
或amount
值..例如/api/values/getnotice/0/2
不起作用..当然你必须在服务器端编程,请看我的第一句话。否则你每次都会得到所有数据,但我不知道如何让它起作用..基本上是存储过程正在返回所有数据。您是否建议我创建一个每次执行发送两个项目的SP?我了解逻辑,但如何实现它?如何将索引值分配给(time_scrolled*2)或(time_scrolled*2+1)??那么索引0或1处的数据呢?已经编辑了答案并编写了完整的代码,请看一看。感谢您的回答,但不幸的是,应用上述代码会停止我的滚动事件,即滚动上没有加载任何数据。实际上,我的CallMoreData是custome JQuery库中具有滚动功能的函数。您可以如何获取完整的代码?以便我能提供更多帮助。请查看我编辑的问题。这是所有执行滚动功能以及从api获取数据的代码。。。