Race-condition when submitting form with jQuery

2019-08-15 20:38发布

问题:

I have to do a hack in order to be able to submit a form (non-ajax) using jQuery.

If I don't do the if statement the form won't submit:

This works (Form gets submitted)

$("#myHiddenFieldID").val(JSON.stringify(jsObject));
var x = $("#myHiddenFieldID").val();
if (x) {
    $("#myHiddenForm").submit();
}

This doesn't work (form does not get submitted field stays empty)

$("#myHiddenFieldID").val(JSON.stringify(jsObject));
var x = $("#myHiddenFieldID").val();
// I used to put an alert here, which was shown __before__ the text appeared in the text field???!!! 
$("#myHiddenForm").submit();

I don't understand, why I have to read the textfields content here...

回答1:

Due to hoisting, the assignment statement is executed before the value is passed to the text field:

var x = $("#myHiddenFieldID").val();
$("#myHiddenFieldID").val(JSON.stringify(jsObject));
$("#myHiddenForm").submit();