概要
很多时候为了兼容性问题 和 上传文件问题,我们会选择 以 formData 为发送数据类型进行 ajax 异步请求。
代码
<form method="post" action="/cart/add" id="upload_form" accept-charset="UTF-8" class="shopify-product-form" enctype="multipart/form-data">
<input type="hidden" name="form_type" value="product">
<input type="hidden" name="utf8" value="✓">
<select name="id">
<option value="35293996253349" selected="selected">red</option>
<option value="35293996286117">blue</option>
<option value="35293996318885">green</option>
</select>
<p class="line-item-property__field">
<label for="monogram">Monogram (up to 3 letters)</label>
<input required="" id="monogram" style="width:120px; max-width:100%;" type="text" name="properties[Monogram]">
</p>
<p class="line-item-property__field">
<label for="custom_photo">Photo (JPG or PNG)</label>
<input required="" id="custom_photo" type="file" name="properties[Photo]">
</p>
<!-- 提交 -->
<button id="upload_form_submit" class="btn">提交</button>
</form>
$("#upload_form_submit").click(function (e) {
const _form = $("#upload_form");
const form_type = _form.find("input[name=form_type]").val();
const utf8 = _form.find("input[name=utf8]").val();
const id = _form.find("select[name=id]").val();
const monogram = _form.find("input[name='properties[Monogram]']").val();
const photo = _form.find("input[name='properties[Photo]']").val();
const photoFile = _form.find("input[name='properties[Photo]']")[0].files[0];
// 获取数据 formData 数据
const formData = new FormData();
formData.append('form_type', form_type);
formData.append('utf8', utf8);
formData.append('id', id);
formData.append('properties[Monogram]', monogram);
formData.append('properties[Photo]', photoFile);
// formData 的异步请求
var jqXHR = $.ajax({
type: 'post',
data: formData,
dataType: 'json',
url: '/cart/add',
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success: (res) => {
console.log(res);
},
error: (err) => {
console.log(err);
}
});
});