jquery ajax success problem
Why is it that the following s开发者_开发百科cript works clientside by removing the relievant html entity:
$(".ui-delete").click(function() {
$.ajax({
url: 'delete.aspx',
type: 'POST',
data: { strWidgetID:$(this).parents(".widget").attr("id") },
error: function() { alert('Error'); },
success: function() { alert('Success'); }
});
$(this).parents(".widget:first").remove();
});
But the following query which is "more proper", does not work by removing the html entity?
$(".ui-delete").click(function() {
$.ajax({
url: 'delete.aspx',
type: 'POST',
data: { strWidgetID:$(this).parents(".widget").attr("id") },
error: function() { alert('Error'); },
success: function() {
alert('Success');
$(this).parents(".widget:first").remove();
}
});
});
The first script does both clientside and serverside correctly, the second script does serverside correctly, but on clientside, it just displays an alert "success", but does not remove the html entity "widget"
Any ideas?
Within the success handler, this
isn't what it was in your click handler (it's the XMLHttpRequest object that $.ajax used).
Capture a reference to the this
you're interested in before the $.ajax call:
$(".ui-delete").click(function() {
var that = this;
$.ajax({
// etc.
success: function() {
$(that).parents('.widget:first').remove();
}
});
};
Based on the context, $(this) refers different objects. Check out this link What is this? In the second codesample, this refers to the ajax settings object and not the 'ui-delete' element.
精彩评论