Vik*_*ant 1 javascript asp.net ajax jquery
在这里,我有一个函数需要在.NET项目中出现的任何AJAX调用之前调用.
目前,我必须调用checkConnection每个按钮点击将调用AJAX方法,如果有网络连接,则进入实际的AJAX调用!
无论如何,我想避免这种方式,并且checkConnection应该在窗体上的任何AJAX调用之前自动调用该函数.
简而言之,我希望使函数的行为类似于event在任何AJAX调用之前触发的函数
添加样本,使点击按钮时调用AJAX; 当然,在检查互联网可用性后......
//check internet availability
function checkConnection() {
//stuff here to check internet then, set return value in the variable
return Retval;
}
//Ajax call
function SaveData() {
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
Run Code Online (Sandbox Code Playgroud)
以下是当前呼叫功能的方式:
<form onsubmit="return Save();">
<input type="text" id="txtYears" /><br />
<input type="submit" id="btnSave" onclick="return checkConnection();" value="Save" />
<script>
function Save() {
if (confirm('Are you sure?')) {
SaveData();
}
else {
return false;
}
}
</script>
</form>
Run Code Online (Sandbox Code Playgroud)
如果没有在JavaScript中实际编写一次调用(!),则无法隐式调用函数.
所以,最好在实际中调用它,AJAX为此你可以beforeSend像下面这样使用ajaxRequest的属性,因此不需要checkConnection()单独调用:
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
beforeSend: function() {
if(!checkConnection())
return false;
},
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
Run Code Online (Sandbox Code Playgroud)
它减少了你onsubmit()对form标签的调用!
更新:在每个AJAX请求使用之前注册一个全局函数:
$(document).ajaxSend(function() {
if(!checkConnection())
return false;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11902 次 |
| 最近记录: |