简体   繁体   中英

Javascript AJAX request problems

I'm having a problem executing a certain bit of AJAX. Here is how I want to happen:

I have a form where upon pressing a button I want to execute a small bit of Javascript (confirm the execution of the action), send an AJAX request, and then submit the form. I don't care about the output of the AJAX request, but it needs to run before the form is submitted.

The button is defined as:

<input title="Delete" onclick="return check_delete('id');" 
type="submit" name="Delete" value="Delete">

The function check_delete is:

var sure = confirm('Are you sure you want to delete this?');
if (!sure) return false;

var del = confirm('Would you like to delete related content?');
if (window.XMLHttpRequest) {
    xmlhttp=new XMLHttpRequest();
} else {
    xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
}
var url = '/del_check.php&id='+id+'&del='+del;

xmlhttp.open('GET',url,true);
xmlhttp.send();
return true;

The function runs fine, except for the xmlhttp.send() part - the request does not show up in the web-server's logs, and does not get executed. After playing with it a bit, I found that if I change the last line in the function to return false instead of true , my AJAX starts working, however, because of the false return value, the form does not get submitted.

What am I missing?

This line:

xmlhttp.open('GET',url,true);

means you're issuing an asynchronous request ( MSDN , W3C ). The request is initiated by your code, but your code doesn't block waiting for it to complete (which is normally a Good Thing tm ).

However, when you submit a form, the page is torn down and replaced with the result of the form submission. Any outstanding or queued ajax requests will be aborted or never even started.

You could make the request synchronous (blocking) by changing that true to a false , but then you'll lock up the page (at best) or the browser (at worst) until that request completes, which isn't ideal.

Alternatives are to avoid doing the ajax request entirely, or to cancel the form submission, wait for the ajax response (even though you don't care about it), and then submit the form programmatically (via HTMLFormElement#submit — eg, calling submit on the form 's DOM element). If you do that second one, note that the button you clicked won't be included in the form data unless you manually insert it, since the form is no longer being submitted by that button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM