Another option is to use an iframe and set the form's target to it.
You can try this (it uses jQuery):
function ajax_form($form, on_complete) { var iframe; if (!$form.attr('target')) { //為表單創(chuàng)建一個(gè)唯一的iframe iframe = $("<iframe></iframe>").attr('name', 'ajax_form_' + Math.floor(Math.random() * 999999)).hide().appendTo($('body')); $form.attr('target', iframe.attr('name')); } if (on_complete) { iframe = iframe || $('iframe[name="' + $form.attr('target') + '"]'); iframe.load(function () { //獲取服務(wù)器響應(yīng) var response = iframe.contents().find('body').text(); on_complete(response); }); } }
It works in all browsers, you don't need to serialize or prepare the data. One drawback is that you can't monitor progress.
Also, at least for Chrome, the request does not appear under the "xhr" tab of the developer tools, but under "doc".
The problem I had was using the wrong jQuery identifier.
You can use a formUse ajax to upload data and files.
PHP HTML
<?php print_r($_POST); print_r($_FILES); ?> <form id="data" method="post" enctype="multipart/form-data"> <input type="text" name="first" value="Bob" /> <input type="text" name="middle" value="James" /> <input type="text" name="last" value="Smith" /> <input name="image" type="file" /> <button>提交</button> </form>
jQuery Ajax
$("form#data").submit(function(e) { e.preventDefault(); var formData = new FormData(this); $.ajax({ url: window.location.pathname, type: 'POST', data: formData, success: function (data) { alert(data) }, cache: false, contentType: false, processData: false }); });
Simplified version
$("form#data").submit(function(e) { e.preventDefault(); var formData = new FormData(this); $.post($(this).attr("action"), formData, function(data) { alert(data); }); });