当用户单击“清除”按钮时,我试图只刷新页面的一部分,目前我正在使用一些代码,我破解了我在此处找到的另一个答案:
$('.clear').click(function () {
$.ajax({
url: "",
context: document.body,
success: function (s, x) {
$(this).html(s);
}
});
});
这会重新加载整个文档主体,我如何定位特定的 div 或类?
context: document.body.somediv?
最佳答案
jQuery API关于 context
选项:
This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). For example, specifying a DOM element as the context will make that the context for the complete callback of a request, like so:
$.ajax({ url: "test.html", context: document.body }).done(function() { $( this ).addClass( "done" ); });
所以,context
选项就是在回调函数中设置this
对象的作用域。默认情况下,它是 ajax 对象,具有当前配置:
$.ajax({
url: ""
}).done(function(){
console.log(this);
// logs: { url: "", type: "GET", etc... }
//
});
如果您希望针对特定部分加载响应,您只需使用 jQuery 查找元素并将响应放入该元素,context
与您无关:
$.ajax({
url: "",
}).success(function(data){
// data is your response
$(".some-element").html(data);
});
但是,您可以使用 context
使配置更容易理解,如下所示:
$.ajax({
url: "",
context: $(".some-element")
}).success(function(data){
$(this).html(data);
// $(this) refers to the context object, in this case $(".some-element")
});
如果您现在希望将 ajax 响应加载到页面的其他位置,您只需更改 context
参数上的选择器即可。
关于jquery - 使用 Ajax 上下文刷新页面的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20349955/