Est*_*ban 3 javascript jquery jquery-events
设想
我正在编写一个 Web 应用程序,在我的例子中是 MVC,我需要使用 get 请求的响应来更新特定容器,有时我想过滤元素并从响应中找到一个元素以放入原始容器中。
我该怎么做?
当我需要异步部分更新我的内容时,我正在构建一个 Web 应用程序
所以我想出了一个可能也适合您需求的功能。
基本上,它将对提供的 url 执行 get 请求,它具有标准 jQuery 回调:onSuccess、onError和onComplete,并且您可以对结果进行 filter() 和 find() 以及指定将响应放入的容器。
假设您的页面上有此内容:
<div id="myContentWrapper">
<div class="myContent">
<h1>This is the content I want to update.</h1>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
请求的响应返回以下内容:
<html>
<!-- some html -->
<div id="filterId">
<div class="findClass">
<h1>This is the content I want to inject!</h1>
</div>
</div>
<!-- some more html -->
</html>
Run Code Online (Sandbox Code Playgroud)
现在您可以更新它,将函数连接到myButton单击事件:
$("#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');
});
});
Run Code Online (Sandbox Code Playgroud)
很简单,现在该函数将为您完成其余的工作:
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 = "<h1>An error occurred!</h1>";
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);
}}});}
Run Code Online (Sandbox Code Playgroud)
也许您不想在响应中过滤或查找某些内容,所以您可以这样做:
loadContent("/Controller/Action", null, null,
"div#myContentWrapper div.myContent",
function() {
alert('Success!');
}, function () {
alert('Error :(');
}, function () {
alert('Complete');
});
Run Code Online (Sandbox Code Playgroud)
或者也许您不需要任何回调:
//This is the basic function call, these parameters are required
loadContent("/Controller/Action", null, null,
"div#myContentWrapper div.myContent",
null, null, null);
Run Code Online (Sandbox Code Playgroud)
好了,现在您可以轻松地异步更新您想要的任何内容,请随意根据需要进行调整,您也可以使用请求类型参数,以便您可以 GET 或 POST,甚至添加图像容器的 id,以便您可以显示loading它当您输入该函数并将其隐藏在 $.ajax 的完整回调中时。
| 归档时间: |
|
| 查看次数: |
3621 次 |
| 最近记录: |