jQuery Dialog form serialize reposting incorrect data on subsequent uses
I'm working with forms inside jQuery Dialog, and am having some issues with the data it's posting. First load and save works fine, posts the correct data. Until I refresh the page though, every subsequent load seems to work, as in the correct data is in the form, however, when saved, the data from the first load is what is posted every time.
function formdialog(url, tack, divid, scriptload){
$.getJSON(url+tack+"/form", function(data){
var formwin = '<div><form id="formdialog">'+data['form']+'</form></div>';
var dialog = $(formwin).dialog({
title: data['title'],
autoOpen: false,
modal: true,
buttons: {
"Save": function(){
$.post(url+tack+"/process",
$("#formdialog").serialize(),
function(data){
开发者_如何转开发 alert($("#formdialog").serialize());
$(this).dialog('close');
$(this).remove();
}
);
},
"Cancel": function(){$(this).dialog('close'); $(this).remove();}
}
});
dialog.dialog("open");
});
}
$(function(){
$("a.edlnk").click(function(){
var url = $(this).attr("href");
formdialog(CONFIG_HREF_SITE+"ajax/"+appControl, "/"+url, divid);
return false;
});
});
I believe the problem is the
$(this).dialog('close');
$(this).remove();
...in your post
callback, because you haven't specified the context for the callback. If so, changing the post
to this should fix it:
$.ajax({
url: url+tack+"/process",
type: 'POST',
data: $("#formdialog").serialize(),
context: this,
success: function(data){
alert($("#formdialog").serialize());
$(this).dialog('close');
$(this).remove();
}
});
...because then you're preserving the meaning of this
when the success
function is called.
So why would that issue cause the behavior you're seeing? Because if you're not removing the formwin
div
, you're not removing the formdialog
form
, which means you end up with multiple form
s on the page with the same ID. Although having the same ID on multiple elements is invalid and therefore subject to undefined behavior, most browsers will give you the first matching element when you ask for an element by ID — which in your case would be the earlier form with the earlier data.
Edit Re your comment: Yeah, I kind of missed the $(this).dialog('close')
there. :-) A couple of options: One is to remember $(formwin)
in a local variable and then use it in the callback, e.g.:
var formwin = '<div><form id="formdialog">'+data['form']+'</form></div>';
var formwinElement = $(formwin); // <== Remember it here
var dialog = formwinElement.dialog({ // <== Use it here
// ...
$.post(url+tack+"/process",
$("#formdialog").serialize(),
function(data){
alert($("#formdialog").serialize());
$(this).dialog('close');
formWinElement.remove(); // <== And again here
}
);
...and don't bother with the context
param (hence my using your original $.post
in this update). That works because the post
success handler is a closure over the formwinElement
variable (and several other things).
精彩评论