如何使用javascript异步更新我的内容
How to update my content async with javascript?
场景
我正在编写一个 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>
请求的响应返回以下内容:
<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>
现在您可以更新它连接函数以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');
});
});
很简单,现在该功能将为您完成其余的工作:
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);
}}});}
也许您不想在响应中过滤或查找某些内容,因此您可以执行以下操作:
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 的完整回调中隐藏它。
相关文章:
- 如何检查Json文件更新,如果更新了,则用更新的数据刷新我的页面
- Angular没有根据模型更新我的选择元素
- 更新数据,而不是用javascript和jquery将其添加到我的表中
- 为什么ngModelCtrl$脏不在我的指令中更新
- 如何使用ng repeat中的选定输入更新我的对象
- 更新Wordpress和我的平滑滚动停止工作
- 为什么我的文本框没有用查询结果更新
- 如何在 D3 中更新我的多折线图数据
- 更新/销毁我的观点,我相信我的逻辑可能需要注意
- 为什么我的状态在 React.js 中没有更新
- 如何使用javascript异步更新我的内容
- 为什么我的 cshtml 页面的 javascript 没有在浏览器中更新/刷新
- 值更改我的链接而不更新
- 我希望我的php/html网站上的JavaScript能够实时更新
- knockout.js获胜't更新我的foreach绑定,尽管更改已注册
- 如何在不按ctrl+F5的情况下更新我的Web应用程序(chrome、mozilla、IE8+)更改
- 为什么'这些AJAX调用正在更新我的变量
- 我的服务没有更新-Angularjs
- 如何使用错误消息或成功消息动态更新我的跨度
- 为什么我的更新页面不工作