Method to call JavaScript AJAX function on page leave
I have a web page with a form, a submit button for that form, and a link that takes a user to another page. I want to upload whatever changes I've made to that form to the server (a PHP script that will save the values) when a user clicks that link to take them to another page.
What is the best event to bind开发者_开发技巧 a JavaScript ajax function so that the form gets passed to the server and the user is then redirected to the next page?
One way is to redirect on the server side,
If using php:
header("Location: new_page.php"); //involves no javascript
Another way is to use javascript ajax, i use jQuery:
$('form').submit(function(e){
e.preventDefault();
$.ajax(
{
url: this.action,
data: $(this).serialize(),
success: function(){
window.location = 'newpage';//redirect on success
}
}
)
})
If you don't mind jQuery,
$("#yourlink").click(function (event) {
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
});
location.href("your link"); //actually, i'm pretty sure the link will go ahead and fire anyways without this...
});
精彩评论