这是一个有效的jquery回调函数调用吗? [英] Is this a valid jquery callback function call?
问题描述
我执行这样的函数,
< script type =text / javascript>
$(document).ready(function(){
getEntities(Clients / GetClients,0,formatClientsResult);
var maxvalues = #HfId)。val();
$(。pager)。pagination(maxvalues,{
callback:getEntities(Clients / GetClients,formatClientsResult),
current_page:0 ,
items_per_page:5,
num_display_entries:5,
next_text:'Next',
prev_text:'Prev',
num_edge_entries:1
} ;
});
< / script>
$(function(){
$ .ajaxSetup({
contentType:'application / json; charset = utf-8',
global:false,
async:false,
dataType:'json',
beforeSend:function(){$('。loading')。show();},
complete:function {$('。loading')。hide();}
});
});
function getEntities(url,currentPage,formatResultFunction){
$ .ajax({
url:url,
data:{'currentPage':(currentPage + 1 ),'pageSize':5},
success:function(data){
if(data.isRedirect&& data.isRedirect === true){
alert重定向到+ data.redirectUrl);
location ='http://www.google.com';
}
else {
var divs ='';
$(#hfId)。val('');
$(#ResultsDiv)。empty();
$ .each(data.Results,function $ b divs + = formatResultFunction(this);
});
$(#ResultsDiv)。append(divs);
$(。resultsdiv:even)。addClass resultseven);
$(。resultsdiv)。hover(function(){
$(this).addClass(resultshover);
},function b $ b $(this).removeClass(resultshover);
});
$(#HfId)。val();
$(#HfId)。val(data.Count);
}
}
});
return false;
}
function formatClientsResult(result){
return'< div class =resultsdiv>< br />< span style = display:inline-block; width:220px; class =resultName>'+ result.ClientName +'< / span>< span class =resultfieldsstyle =padding-left:10px;> Mobile No& nbsp;:< / span> & nbsp;< span class =resultfieldvalues>'+ result.ClientMobNo +'< / span>< span style =float:right; padding-right:2px;& checkboxvalue ='+ result.ClientId +'onclick =storeIds();/>< / span>< br />< br />< span class =resultfields>地址& nbsp;:< / span>& nbsp;< span class =resultfieldvalues>'+ result.ClientAddress +'< / span>< / div>';
}
我通过firebug检查我发现我的请求,
http:// localhost:1115/0?currentPage = [object + HTMLDivElement] 1& pageSize = 5
... Am i缺少某个...
在初始加载时执行的请求是
http:// localhost:1115 / Clients / GetClients?currentPage = 1& pageSize = 5
这似乎工作,但只有回调函数失败...
正如darin所建议的,
$(document).ready(function(){
getEntities(Clients / GetClients,0,formatClientsResult);
var maxvalues = #HfId)。val();
$(。pager)。pagination(maxvalues,{
callback:function(){
getEntities(Clients / GetClients,0, formatClientsResult);
},
current_page:0,
items_per_page:5,
num_display_entries:5,
next_text:'Next',
prev_text:'Prev'
num_edge_entries:1
});
我的控制器动作,
public JsonResult GetClients(int currentPage,int pageSize)
{
if(Session [userId]!= null)
{
var clients = clirep.FindAllClients(Convert.ToInt32(Session [userId]))。AsQueryable();
var count = clients.Count();
var results = new PagedList< ClientBO>(clients,currentPage_1,pageSize);
var genericResult = new {Count = count,Results = results,isRedirect = false};
return Json(genericResult);
}
else
{
var genericResult = new {redirectUrl = Url.Action(Create,Registration),isRedirect = true};
return Json(genericResult);
}
}
>
public IQueryable< ClientBO> FindAllClients(int userId)
{
var client = from c in taxidb.Clients
其中c.CreatedBy == userId&& c.IsDeleted == 0
选择新的ClientBO()
{
ClientId = c.ClientId,
ClientName = c.ClientName,
ClientMobNo = Convert.ToString c.ClientMobNo),
ClientAddress = c.ClientAddress
};
return client;
}
和我的观点,
<%@ Page Title =Language =C#MasterPageFile =〜/ Views / Shared / Site.MasterInherits =System.Web.Mvc.ViewPage< TaxiMVC.Models.Client> %>
< asp:Content ID =Content1ContentPlaceHolderID =TitleContentrunat =server>
索引
< / asp:Content>
< asp:Content ID =Content2ContentPlaceHolderID =MainContentrunat =server>
< h2>
客户< / h2>
< input type =hiddenid =hfId/>
< input type =hiddenid =hfEditId/>
< div id =ErrorDiv>
< / div>
< div id =ImageButtonDiv>
< input type =buttonclass =addbuttonsonclick =return showadd(); />
< input type =buttonclass =editbuttonsonclick =if(editdetails()){return getClientbyId($('#hfld')。val());}/>
< input type =buttonclass =deletebuttonsonclick =if(deletedetails()){return deleteClients($('#hfId')。val());}
< / div>
< div id =ResultsDiv>
< / div>
< div id =PagerDownclass =pager>
< / div>
< div id =adddivstyle =display:none;>
< form id =addformautocomplete =offaction =>
< fieldSet>
< legend>客户详细信息< / legend>
< table cellpadding =0cellspacing =0width =100%>
< tr>
< td class =tdfieldsstyle =width:25%; padding-right:20px; align =right>
客户名称& nbsp;:
< / td>
< td style =width:20%;>
<%= Html.TextBox(Name,null,new {@class =text_box_height_14_width_150})%>
& nbsp;
< / td>
< td style =width:55%; class =status>
& nbsp;
< / td>
< / tr>
< tr>
< td class =tdfieldsstyle =width:25%; padding-right:20px; align =right>
Mobile No& nbsp;:
< / td>
< td style =width:20%;>
<%= Html.TextBox(MobileNo,null,new {@class =text_box_height_14_width_150})%>
& nbsp;
< / td>
< td style =width:55%; class =status>
& nbsp;
< / td>
< / tr>
< tr>
< td class =tdfieldsstyle =width:25%; padding-right:20px; align =right>
地址& nbsp;:
< / td>
< td style =width:20%;>
<%= Html.TextArea(Address,null,6,42,new {@class =multiline_text_box_height_14_width_200})%&
& nbsp;
< / td>
< td style =width:55%; class =status>
& nbsp;
< / td>
< / tr>
< tr>
< td colspan =2align =center>
< div class =form-submit>
< input type =submitvalue =Submitid =submit/>
& nbsp;& nbsp;< input type =buttonvalue =Cancelid =cancelonclick =return showResultsdiv() />
< / div>
< / td> ¥b $ b< td>
< / td>
< / tr>
< / table>
< / fieldset>
< / form>
< / div>
< input id =HfIdtype =hidden/>
< script type =text / javascript>
$(document).ready(function(){
// getClients(0);
getEntities(Clients / GetClients,0,formatClientsResult);
var maxvalues = $(#HfId)。val();
$(。pager)。pagination(maxvalues,{
callback:function(){
getEntities(Clients / GetClients ,0,formatClientsResult);
},
current_page:0,
items_per_page:5,
num_display_entries:5,
next_text:'Next',
prev_text:'Prev',
num_edge_entries:1
});
var validator = $(#addform)。validate({
rules:{
名称:required,
MobileNo:{
required:true,
number:true,
minlength:10
},
:required
},
消息:{
名称:请提供客户名称,
MobileNo:{
提供手机号码,
号码:请提供手机号码,
rangelength:jQuery.format(至少输入{0}个字符)
},
地址:请提供客户端地址
},
// errorPlacement已将表布局视为
errorPlacement:function(error,element){
错误.appendTo(element.parent()。next());
},
//将此类设置为error-labels以指示有效字段
success:function(label){
// set&作为IE
label.html(& nbsp;)的文本。addClass(checked);
},
submitHandler:function(form){
if($(#hfEditId)。val()==){
$。 ajax({
url:Clients / ClientCreate,
data:{'clientName':$(#Name)。val(),'clientMobNo':$(#MobileNo)。 val(),'clientAddress':$(#Address)。val()},
contentType:application / json; charset = utf-8,
global:false,
async:false,
dataType:json,
beforeSend:function(){$('。loading')。show();},
complete:function ('.loading')。hide();},
success:function(data){
if(data.Result ==Success){
$(#hfEditId ).val('');
$(#addform)。clearForm();
getEntities(Clients / GetClients,0,formatClientsResult);
$(#adddiv)。hide();
$(#ResultsDiv)。show();
$(#PagerDown)。show();
$(#ImageButtonDiv)。show();
var maxvalues = $(#HfId)。val();
$(。pager)。pagination(maxvalues,{
callback:getEntities(Clients / ClientCreate,0,formatClientsResult),
current_page:0,
items_per_page: 5,
num_display_entries:5,
next_text:'Next',
prev_text:'Prev',
num_edge_entries:1
}
$(#alert)。remove();
topBar('successfully added');
return false;
}
}
});
}
else {
$ .ajax({
url:Clients / Clientupdate,
data:{'clientId':$(#hfEditId) .val(),'clientName':$(#Name)。val(),'clientMobNo':$(#MobileNo)。val(),'clientAddress':$(#Address)。val ()},
contentType:application / json; charset = utf-8,
global:false,
async:false,
dataType:json,
beforeSend:function(){$('。loading')。show();},
complete:function(){$('。 success:function(data){
if(data.Result ==Success){
$(#hfEditId)。val('');
$(#addform ).clearForm();
getEntities(Clients / GetClients,0,formatClientsResult);
$(#adddiv)。hide();
$(#ResultsDiv)。show();
$(#PagerDown)。show();
$(#ImageButtonDiv)。show();
var maxvalues = $(#HfId)。val();
$(。pager)。pagination(maxvalues,{
callback:getEntities(Clients / Clientupdate,0,formatClientsResult),
current_page:0,
items_per_page: 5,
num_display_entries:5,
next_text:'Next',
prev_text:'Prev',
num_edge_entries:1
}
$(#alert)。remove();
topBar('successfully updated');
return false;
}
}
});
}
}
});
});
< / script>
< / asp:Content>
getEntities
function期望有3个参数。这里你只传递2:
callback:getEntities(Clients / GetClients,formatClientsResult)
此外,第二个参数需要是一个整数而不是另一个函数。因为它是一个回调,它需要被定义为:
callback:function(){
getEntities Clients / GetClients,0,formatClientsResult);
}
UPDATE:
你总是得到相同的AJAX请求的原因是你总是传递0到 getEntities =http://d-scribe.de/webtools/jquery-pagination/lib/jquery_pagination/README =nofollow noreferrer>分页回调。
请尝试以下操作:
$(。pager)。分页(maxvalues,{
callback:function(new_page_index,pagination_container){
//注意new_page_index如何传递
getEntities(home / GetClients,new_page_index,formatClientsResult);
},
current_page:0,
items_per_page:5,
num_display_entries:5,
next_text:'Next',
prev_text:'Prev',
num_edge_entries:1
});
I executing a function like this,
<script type="text/javascript"> $(document).ready(function() { getEntities("Clients/GetClients", 0, formatClientsResult); var maxvalues = $("#HfId").val(); $(".pager").pagination(maxvalues, { callback: getEntities("Clients/GetClients", formatClientsResult), current_page: 0, items_per_page: 5, num_display_entries: 5, next_text: 'Next', prev_text: 'Prev', num_edge_entries: 1 }); }); </script> $(function() { $.ajaxSetup({ contentType: 'application/json; charset=utf-8', global: false, async: false, dataType: 'json', beforeSend: function() { $('.loading').show(); }, complete: function() { $('.loading').hide(); } }); }); function getEntities(url, currentPage, formatResultFunction) { $.ajax({ url: url, data: { 'currentPage': (currentPage + 1), 'pageSize': 5 }, success: function(data) { if (data.isRedirect && data.isRedirect === true) { alert('must redirect to ' + data.redirectUrl); location = 'http://www.google.com'; } else { var divs = ''; $("#hfId").val(''); $("#ResultsDiv").empty(); $.each(data.Results, function() { divs += formatResultFunction(this); }); $("#ResultsDiv").append(divs); $(".resultsdiv:even").addClass("resultseven"); $(".resultsdiv").hover(function() { $(this).addClass("resultshover"); }, function() { $(this).removeClass("resultshover"); }); $("#HfId").val(""); $("#HfId").val(data.Count); } } }); return false; } function formatClientsResult(result) { return '<div class="resultsdiv"><br /><span style="display: inline-block;width:220px;" class="resultName">' + result.ClientName + '</span><span class="resultfields" style="padding-left:10px;">Mobile No :</span> <span class="resultfieldvalues">' + result.ClientMobNo + '</span><span style="float:right; padding-right:2px;"><input type="checkbox" value=' + result.ClientId + ' onclick="storeIds();"/></span><br/><br/><span class="resultfields">Address :</span> <span class="resultfieldvalues">' + result.ClientAddress + '</span></div>'; }
and i inspected through firebug i found my request was,
http://localhost:1115/0?currentPage=[object+HTMLDivElement]1&pageSize=5
... Am i missing something...When executing on initial load the request is,
http://localhost:1115/Clients/GetClients?currentPage=1&pageSize=5
This seems to work but Only the callback function fails...
I am using this jquery pagination plugin
As suggested by darin,
$(document).ready(function() { getEntities("Clients/GetClients", 0, formatClientsResult); var maxvalues = $("#HfId").val(); $(".pager").pagination(maxvalues, { callback: function() { getEntities("Clients/GetClients", 0, formatClientsResult); }, current_page: 0, items_per_page: 5, num_display_entries: 5, next_text: 'Next', prev_text: 'Prev', num_edge_entries: 1 });
My controller action,
public JsonResult GetClients(int currentPage, int pageSize) { if (Session["userId"]!=null) { var clients = clirep.FindAllClients(Convert.ToInt32(Session["userId"])).AsQueryable(); var count = clients.Count(); var results = new PagedList<ClientBO>(clients, currentPage - 1, pageSize); var genericResult = new { Count = count, Results = results ,isRedirect=false}; return Json(genericResult); } else { var genericResult = new {redirectUrl = Url.Action("Create", "Registration"), isRedirect = true }; return Json(genericResult); } }
And my model,
public IQueryable<ClientBO> FindAllClients(int userId) { var client = from c in taxidb.Clients where c.CreatedBy == userId && c.IsDeleted == 0 select new ClientBO() { ClientId = c.ClientId, ClientName= c.ClientName, ClientMobNo= Convert.ToString(c.ClientMobNo), ClientAddress= c.ClientAddress }; return client; }
and my view,
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TaxiMVC.Models.Client>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Index </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2> Clients</h2> <input type="hidden" id="hfId" /> <input type="hidden" id="hfEditId" /> <div id="ErrorDiv"> </div> <div id="ImageButtonDiv"> <input type="button" class="addbuttons" onclick="return showadd();" /> <input type="button" class="editbuttons" onclick="if(editdetails()){return getClientbyId($('#hfId').val());}" /> <input type="button" class="deletebuttons" onclick="if(deletedetails()){return deleteClients($('#hfId').val());}" /> </div> <div id="ResultsDiv"> </div> <div id="PagerDown" class="pager"> </div> <div id="adddiv" style="display: none;"> <form id="addform" autocomplete="off" action=""> <fieldset> <legend>Client Details</legend> <table cellpadding="0" cellspacing="0" width="100%"> <tr> <td class="tdfields" style="width: 25%; padding-right: 20px;" align="right"> Client Name : </td> <td style="width: 20%;"> <%= Html.TextBox("Name", null, new { @class = "text_box_height_14_width_150" })%> </td> <td style="width: 55%;" class="status"> </td> </tr> <tr> <td class="tdfields" style="width: 25%; padding-right: 20px;" align="right"> Mobile No : </td> <td style="width: 20%;"> <%= Html.TextBox("MobileNo", null, new { @class = "text_box_height_14_width_150" })%> </td> <td style="width: 55%;" class="status"> </td> </tr> <tr> <td class="tdfields" style="width: 25%; padding-right: 20px;" align="right"> Address : </td> <td style="width: 20%;"> <%= Html.TextArea("Address", null, 6, 42, new { @class = "multiline_text_box_height_14_width_200" })%> </td> <td style="width: 55%;" class="status"> </td> </tr> <tr> <td colspan="2" align="center"> <div class="form-submit"> <input type="submit" value="Submit" id="submit" /> <input type="button" value="Cancel" id="cancel" onclick="return showResultsdiv();" /> </div> </td> <td> </td> </tr> </table> </fieldset> </form> </div> <input id="HfId" type="hidden" /> <script type="text/javascript"> $(document).ready(function() { // getClients(0); getEntities("Clients/GetClients", 0, formatClientsResult); var maxvalues = $("#HfId").val(); $(".pager").pagination(maxvalues, { callback: function() { getEntities("Clients/GetClients", 0, formatClientsResult); }, current_page: 0, items_per_page: 5, num_display_entries: 5, next_text: 'Next', prev_text: 'Prev', num_edge_entries: 1 }); var validator = $("#addform").validate({ rules: { Name: "required", MobileNo: { required: true, number: true, minlength: 10 }, Address: "required" }, messages: { Name: "please provide a client name", MobileNo: { required: "Please provide a mobile phone no", number: "Please provide a mobile phone no", rangelength: jQuery.format("Enter at least {0} characters") }, Address: "please provide client address" }, // the errorPlacement has to take the table layout into account errorPlacement: function(error, element) { error.appendTo(element.parent().next()); }, // set this class to error-labels to indicate valid fields success: function(label) { // set as text for IE label.html(" ").addClass("checked"); }, submitHandler: function(form) { if ($("#hfEditId").val() == "") { $.ajax({ url: "Clients/ClientCreate", data: { 'clientName': $("#Name").val(), 'clientMobNo': $("#MobileNo").val(), 'clientAddress': $("#Address").val() }, contentType: "application/json; charset=utf-8", global: false, async: false, dataType: "json", beforeSend: function() { $('.loading').show(); }, complete: function() { $('.loading').hide(); }, success: function(data) { if (data.Result == "Success") { $("#hfEditId").val(''); $("#addform").clearForm(); getEntities("Clients/GetClients", 0, formatClientsResult); $("#adddiv").hide(); $("#ResultsDiv").show(); $("#PagerDown").show(); $("#ImageButtonDiv").show(); var maxvalues = $("#HfId").val(); $(".pager").pagination(maxvalues, { callback: getEntities("Clients/ClientCreate", 0, formatClientsResult), current_page: 0, items_per_page: 5, num_display_entries: 5, next_text: 'Next', prev_text: 'Prev', num_edge_entries: 1 }); $("#alert").remove(); topBar('successfully added'); return false; } } }); } else { $.ajax({ url: "Clients/Clientupdate", data: { 'clientId': $("#hfEditId").val(), 'clientName': $("#Name").val(), 'clientMobNo': $("#MobileNo").val(), 'clientAddress': $("#Address").val() }, contentType: "application/json; charset=utf-8", global: false, async: false, dataType: "json", beforeSend: function() { $('.loading').show(); }, complete: function() { $('.loading').hide(); }, success: function(data) { if (data.Result == "Success") { $("#hfEditId").val(''); $("#addform").clearForm(); getEntities("Clients/GetClients", 0, formatClientsResult); $("#adddiv").hide(); $("#ResultsDiv").show(); $("#PagerDown").show(); $("#ImageButtonDiv").show(); var maxvalues = $("#HfId").val(); $(".pager").pagination(maxvalues, { callback: getEntities("Clients / Clientupdate", 0, formatClientsResult), current_page: 0, items_per_page: 5, num_display_entries: 5, next_text: 'Next', prev_text: 'Prev', num_edge_entries: 1 }); $("#alert").remove(); topBar('successfully updated'); return false; } } }); } } }); }); </script> </asp:Content>
解决方案The
getEntities
function expects 3 arguments. Here you are passing only 2:callback: getEntities("Clients/GetClients", formatClientsResult)
Also the second argument needs to be an integer and not another function. And as it is a callback it needs to be defined as such:
callback: function() { getEntities("Clients/GetClients", 0, formatClientsResult); }
UPDATE:
The reason you are always getting the same AJAX request is that you always pass 0 to the
getEntities
function in the pagination callback.Try this:
$(".pager").pagination(maxvalues, { callback: function (new_page_index, pagination_container) { // Notice how the new_page_index is passed getEntities("home/GetClients", new_page_index, formatClientsResult); }, current_page: 0, items_per_page: 5, num_display_entries: 5, next_text: 'Next', prev_text: 'Prev', num_edge_entries: 1 });
这篇关于这是一个有效的jquery回调函数调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!