在任何 AJAX 调用之前触发 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29489243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:37:26  来源:igfitidea点击:

trigger a javascript function before on any AJAX call

javascriptjqueryasp.netajax

提问by Vikrant

Here, I have a function which needs to be called before any AJAX call present in the .NET project.

在这里,我有一个函数需要在 .NET 项目中存在的任何 AJAX 调用之前调用。

Currently, I have to call checkConnectionon every button click which is going to invoke AJAX method, if net connection is there, proceeds to actual AJAXcall!
Anyhow, I want to avoid this way and the checkConnectionfunction should be called automatically before any AJAX call on the form.

目前,我必须调用checkConnection将调用 AJAX 方法的每个按钮单击,如果存在网络连接,则继续进行实际的AJAX调用!
无论如何,我想避免这种方式,并且checkConnection应该在表单上的任何 AJAX 调用之前自动调用该函数。

In short, I want to make function behave like an eventwhich will be triggered before any AJAX call

简而言之,我想让函数表现得像event在任何 AJAX 调用之前触发的

Adding sample, which makes AJAX call on button click; Of course, after checking internet availability...

添加示例,在单击按钮时进行 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);
            }
        });
    }

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>

回答by Brijesh Bhatt

You cannot implicitly call a function without actually writing a call even once(!) in JavaScript.

在 JavaScript 中,您不能在没有实际编写调用的情况下隐式调用函数(!)。

So, better to call it in actual AJAXand for that you can use beforeSendproperty of ajaxRequest like following, hence there will be no need to call checkConnection()seperately:

因此,最好在实际中调用它,AJAX为此您可以使用beforeSendajaxRequest 的属性,如下所示,因此无需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);
            }
        });

It reduces the call that you have made onsubmit()of formtag!

它减少了您onsubmit()form标签的调用!

UPDATE: to register a global function before every AJAX request use:

更新:在每个 AJAX 请求使用之前注册一个全局函数:

$(document).ajaxSend(function() {
  if(!checkConnection())
     return false;
});

回答by Nikos M.

The best way is to use a publish-subsribe pattern to add any extra functions to be called on pre-determined times (either before or after ajax for example).

最好的方法是使用发布订阅模式来添加任何额外的函数,以便在预定的时间(例如在 ajax 之前或之后)调用。

jQuery already supports custom publish-subsrcibe

jQuery 已经支持自定义发布订阅

For this specific example just do this:

对于此特定示例,只需执行以下操作:

//Ajax call
function SaveData(element) {
       var doAjax = true; 
       var YearData = {
            "holiday_date": D.getElementById('txtYears').value
        };
        if (element === myForm) 
        {
           doAjax = checkConnection();
        }
        if ( doAjax )
        {
        $.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);
            }
        });
        }
        else
        {
          // display a message
        }
    }

Hope i understand correctly what you mean.

希望我能正确理解你的意思。

UPDATE:

更新:

in the ifyou can do an additional check if the function is called from the form or a field (for example add an argument SaveData(element))

if你可以做一个额外的检查,如果函数是从表单或字段调用的(例如添加一个参数 SaveData(element))

If you use the saveData in html, do this: "saveData(this)", maybe you should post your html as well

如果您在 html 中使用 saveData,请执行以下操作:"saveData(this)",也许您也应该发布您的 html

回答by Tell Me How

You can use:

您可以使用:

$(document)
.ajaxStart(function () {
  alert("ajax start");
})
.ajaxComplete(function () {
     alert("ajax complete");
})

That's it!!

而已!!

回答by ozil

use

利用

beforeSend: function () {
},  

ajaxmethod

ajax方法