P粉7941776592023-08-21 09:06:07
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')) { //为表单创建一个唯一的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 () { //获取服务器响应 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".
P粉0644484492023-08-21 00:11:35
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); }); });