尝试使用简写语法通过 jQuery 在 AJAX 请求中上传文件来发送表单数据时,遇到错误“非法调用”。但是,当我使用较长的 .ajax() 方法时,错误消失了。我使用 CodeIgniter 作为服务器端框架。
简写语法错误的原因是什么?为什么 .ajax() 方法可以工作?
形式
<form id="add_category_form" action="<?= base_url("CategoriesController/process_add_category") ?>" method="post" enctype="multipart/form-data">
<input type="hidden" name="<?= $this->security->get_csrf_token_name() ?>" value="<?= $this->security->get_csrf_hash() ?>" />
<h2>Add a Category</h2>
<ul>
<li>
<input type="text" name="name" required>
<label>Category Name</label>
</li>
<li>
<textarea name="description" required></textarea>
<label>Description</label>
</li>
<label>Upload Images (5 Max)</label>
<input type="file" name="image" id="category_image" accept="image/*">
</ul>
<!-- FIXME: center the content of this last li tag -->
<button type="button" data-dismiss="modal" aria-label="Close">Cancel</button>
<button type="submit">Save</button>
</form>
使用$.post
$(document).ready(function() {
$("#add_category_form").submit(function(e) {
e.preventDefault();
let url = $(this).attr("action");
if ($("#category_image").val() == "") {
alert("Please add an image");
} else {
let formData = new FormData(this); // Pass the form element
$.post(url, formData, function(response) {
console.log(response);
csrfName = response.csrfName;
$("input[name='<?= $this->security->get_csrf_token_name() ?>']").val(response.newCsrfToken);
}, "json");
}
return false;
使用$.ajax
$(document).ready(function() {
$("#add_category_form").submit(function(e) {
e.preventDefault();
if ($("#category_image").val() == "") {
alert("Please add an image");
}
let formData = new FormData(this);
$.ajax({
url: "<?= base_url(''); ?>CategoriesController/process_add_category",
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function(response) {
console.log(response);
csrfName = response.csrfName;
$("input[name='<?= $this->security->get_csrf_token_name() ?>']").val(response.newCsrfToken);
},
error: function(xhr, status, error) {
console.error("AJAX Error:", status, error);
}
});
return false;
});
});
使用简写版本的
FormData
时,不能使用 $.post()
对象来存储数据。 文档说第二个参数必须是普通对象或字符串,而不是FormData
。
您需要使用类似于
$.ajax()
的设置对象,以便可以指定 processData: false
。如果没有此选项,它会尝试将对象转换为 URL 编码的字符串。