在任何AJAX调用之前触发javascript函数 [英] trigger a javascript function before on any AJAX call
问题描述
在这里,我有一个需要在.NET项目中存在的任何AJAX调用之前被调用的函数.
Here, I have a function which needs to be called before any AJAX call present in the .NET project.
当前,我必须在要调用AJAX方法的每个按钮单击上调用checkConnection
,如果存在网络连接,则继续进行实际的 AJAX 调用!
无论如何,我想避免这种方式,应该在窗体上的任何AJAX调用之前自动调用checkConnection
函数.
Currently, I have to call checkConnection
on every button click which is going to invoke AJAX method, if net connection is there, proceeds to actual AJAX call!
Anyhow, I want to avoid this way and the checkConnection
function should be called automatically before any AJAX call on the form.
简而言之,我想让函数的行为类似于event
,它将在任何AJAX调用之前触发
In short, I want to make function behave like an event
which will be triggered before any AJAX call
添加样本,点击按钮即可进行AJAX调用;当然,检查互联网可用性之后...
Adding sample, which makes AJAX call on button click; Of course, after checking internet availability...
//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);
}
});
}
以下是当前调用函数的方式:
And below is current way to call function:
<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>
推荐答案
在JavaScript中,即使没有实际编写一次调用,也无法隐式调用函数.
You cannot implicitly call a function without actually writing a call even once(!) in JavaScript.
因此,最好在实际的AJAX
中调用它,为此,您可以使用ajaxRequest的beforeSend
属性,如下所示,因此无需分别调用checkConnection()
:
So, better to call it in actual AJAX
and for that you can use beforeSend
property of ajaxRequest like following, hence there will be no need to call checkConnection()
seperately:
$.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);
}
});
它减少了您对form
标签的onsubmit()
所做的呼叫!
It reduces the call that you have made onsubmit()
of form
tag!
更新: 在每个AJAX请求使用之前注册全局函数:
UPDATE: to register a global function before every AJAX request use:
$(document).ajaxSend(function() {
if(!checkConnection())
return false;
});
这篇关于在任何AJAX调用之前触发javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!