如何使用javascript更新我的内容异步?

脚本

我正在写一个Web应用程序,我的情况下是MVC,我需要使用get请求的响应来更新特定容器,有时我想过滤元素并从响应中找到放置在原始容器中的元素。

我该怎么做?

当我需要异步部分更新我的内容时,我正在构建一个Web应用程序

所以我想出了一个可能也适合你需求的function。

基本上它会对提供的url执行get请求,它有标准的jQuery回调: onSuccessonErroronComplete ,你可以对结果进行filter()和find()以及指定放置响应的容器。

假设您的页面上有此内容:

 

This is the content I want to update.

并且请求的响应返回:

   

This is the content I want to inject!

现在您可以更新它将函数连接到myButton click事件:

 $("#myButton").click(function () { loadContent("/Controller/Action", //url "#filterId", ".findClass", //filter & find "div#myContentWrapper div.myContent", //container to update function () { //success callback alert('Success!'); }, function () { //error callback alert('Error :('); }, function () { //complete callback alert('Complete'); }); }); 

很容易,现在该function将为您完成剩下的工作:

 function loadContent(url, filter, find, container, onSuccess, onError, onComplete) { var htmlResult; $.ajax({ url: url, type: "GET", success: function (data) { htmlResult = data; if (onSuccess && typeof onSuccess == "function") { onSuccess.call(this); } }, error: function () { htmlResult = "

An error occurred!

"; if (onError && typeof onError == "function") { onError.call(this); } }, complete: function () { if (filter != null) { if (find != null) { $(container).html( $(htmlResult).filter(filter).find(find).html()); } else { $(container).html($(htmlResult).find(find).html()); } } else { $(container).html(htmlResult); } if (onComplete && typeof onComplete == "function") { onComplete.call(this); }}});}

也许您不想在响应中过滤或查找内容,因此您可以这样做:

 loadContent("/Controller/Action", null, null, "div#myContentWrapper div.myContent", function() { alert('Success!'); }, function () { alert('Error :('); }, function () { alert('Complete'); }); 

或者您可能不需要任何回调:

 //This is the basic function call, these parameters are required loadContent("/Controller/Action", null, null, "div#myContentWrapper div.myContent", null, null, null); 

你去,现在你可以轻松地异步更新你想要的任何内容,随时根据需要调整它,你也可以使用请求类型参数,这样你可以GET或POST,甚至添加一个loading图像容器的id,这样你就可以显示当你输入函数并将其隐藏在$ .ajax的完整回调时。