如何在使用 MVC 部分视图的任何成功的 Ajax 请求后调用 jQuery 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7030895/
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-08-26 23:18:11  来源:igfitidea点击:

How to call a jQuery function after ANY successful Ajax request with MVC partial views

jqueryajax

提问by Brandon

I have jQuery code that runs fine when a view is render. However, I want this same code to run after an Ajax request is successful. The jQuery was originally performed when the document was ready, but I moved it to it's own function so it can be called. The function adds a few simple classes to some label elements. Here is what I have so far:

我有在渲染视图时运行良好的 jQuery 代码。但是,我希望在 Ajax 请求成功后运行相同的代码。jQuery 最初是在文档准备好时执行的,但我将它移到了它自己的函数中,以便可以调用它。该函数为一些标签元素添加了一些简单的类。这是我到目前为止所拥有的:

$(function () {
    afterLoad();
});

$.ajaxSetup({
    success: function () {
        afterLoad();
    }
});

function afterLoad() {
    // code to execute
}

This doesn't execute properly after making a simple Ajax request:

发出一个简单的 Ajax 请求后,这不会正确执行:

$('#ajaxTest').load('<MVC Route>')

A partial view is returned just fine, but afterLoad()attempts to run before the partial view is in the DOM. If I were to execute the same call again afterLoad()does run (on the previous partial view), but then it gets overwritten by the new partial view.

局部视图返回得很好,但afterLoad()尝试在局部视图进入 DOM 之前运行。如果我再次执行相同的调用,afterLoad()确实会运行(在之前的局部视图上),但是它会被新的局部视图覆盖。

Any thoughts? Another approach to this would be fine, I'm looking for a was to get the site-level .js file to run after an Ajax request for a partial view. The master page loads the site.js file, and I would like to execute it's code without reloading the file (since it's already been loaded by the browser). Also, I don't want to have to force developers to do anything different with their Ajax calls so it needs to work with a simple .load(), etc.

有什么想法吗?另一种方法会很好,我正在寻找一种方法是让站点级 .js 文件在 Ajax 请求局部视图后运行。母版页加载 site.js 文件,我想在不重新加载文件的情况下执行它的代码(因为它已经被浏览器加载了)。另外,我不想强​​迫开发人员对他们的 Ajax 调用做任何不同的事情,所以它需要使用简单的.load()等。

回答by Amin Eshaq

This is what I use for what your trying to do:

这就是我用于您尝试做的事情:

You also have access to the XHR object should you need to access it.

如果需要访问 XHR 对象,您还可以访问它。

//Global Ajax Complete
$("body").bind("ajaxSend", function(e, xhr, settings){
    //Sent
}).bind("ajaxComplete", function(e, xhr, settings){
    //Complete
}).bind("ajaxError", function(e, xhr, settings, thrownError){
    //Error
});

EDIT: This is the structure I have, which has been working for me.

编辑:这是我拥有的结构,它一直在为我工作。

site.js

网站.js

function afterLoad() {
    // code to execute
}
$(document).ready(function(){
    $("body").bind("ajaxComplete", function(e, xhr, settings){
           afterLoad();
    });
});

Created a quick fiddle. is this what you mean?

创建了一个快速小提琴。你是这个意思吗?

Edit Two:

编辑二:

You might want to have a listener on the DOM for any <form>element that appears then run your afterLoad()function. This might be a performance hog so I would use it cautiously.

您可能希望在 DOM 上为<form>出现的任何元素设置一个侦听器,然后运行您的afterLoad()函数。这可能是一个性能猪,所以我会谨慎使用它。

I use livequeryto do this

我使用livequery来做到这一点

$('form').livequery(function(){
    afterLoad();
});

回答by Senad Me?kin

You can set global AJAX defaults in jQuery

您可以在 jQuery 中设置全局 AJAX 默认值

like this

像这样

$.ajaxComplete(function(){
       afterLoad();
    });

so your method will be executed when ajaxCompleted

所以你的方法将在 ajaxCompleted 时执行

回答by Mike

This works fine for me:

这对我来说很好用:

$( document ).ajaxComplete(function( event,request, settings ) {
  //your code here to run when ajax is complete
  alert("Complete");
});

回答by Justin Beckwith

If I'm reading your question right, the issue is that you're attempting to issue 'afterLoad' after the ajax call, but before the partial view elements are added to the DOM. In that case, I think you need to call afterLoad as a part of the ajax load method:

如果我没看错你的问题,问题是你试图在 ajax 调用之后但在将部分视图元素添加到 DOM 之前发出“afterLoad”。在这种情况下,我认为您需要调用 afterLoad 作为 ajax load 方法的一部分:

$('#ajaxTest').load('<MVC Route>', null, 
    function (responseText, textStatus, XMLHttpRequest) 
    { 
        afterLoad(); 
    });

If I'm off base, let me know, happy coding!

如果我不在基地,让我知道,快乐编码!

回答by Mrchief

Remove the ajaxSetup part.

删除 ajaxSetup 部分。

$.ajaxSetup({
/*  success: function () {
     afterLoad();
  }*/
});

And then use loadlike this:

然后load像这样使用:

$('#ajaxTest').load('<MVC Route>', function(){
       afterLoad();
    });

As per the docs, this should work.

根据文档,这应该有效。

回答by ShankarSangoli

The culprit is this

罪魁祸首是这个

$.ajaxSetup({
  success: function () {
     afterLoad();
  }
});

loadinternally uses $.getto fetch the data and when it calls the success handler afterLoadmethod is called before even setting the data into the element. You might have to go with some other approach this will not work.

load内部用于$.get获取数据,当它调用成功处理程序afterLoad方法时,甚至在将数据设置到元素之前调用。您可能不得不采用其他一些方法,这将不起作用。

Try this

尝试这个

    $.ajaxSetup({
      complete: function () {
         afterLoad();
      }
    });

回答by manwhowillsoldtheworld

Above answers didn't worked for me. I wasted a lot of time to figure it out, all in vain. Finally I got a solution that works though in a bit unusual way. Here it is. Basically I am reassigning the event handlers after appending the DOM elements from AJAX

以上答案对我不起作用。我浪费了很多时间来弄清楚,都是徒劳的。最后,我得到了一个解决方案,但它的工作方式有点不寻常。这里是。基本上我在从 AJAX 附加 DOM 元素后重新分配事件处理程序

function autoLoad(){
//write event handlers which you are again going to assign to the ajax appended     dom elements
}

$(document).ready(function(){
autoLoad;
//more event handlers if present (non dynamic DOM elements)
//Any other Jquery stuff
});

$.ajax({    
//send request here
}).done(function(html) {
//unbind the event handlers assigned in autoload function
append ajax results here
autoLoad();
}).fail(function(ts) {
});