如何使用jQuery提交多部分表单数据 [英] How to submit multipart formdata using jquery

查看:167
本文介绍了如何使用jQuery提交多部分表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<form id="uploadForm" enctype="multipart/form-data" action="http://localhost:1337/ad/upload" method="post" name="uploadForm" novalidate>
    <input type="file" name="userPhoto" id="userPhoto" />
    <input type="submit" value="submit" id="uploadImage" />
</form>

这是我的html表单,它接受图像作为文件输入,用户可以选择图像文件,然后单击提交.此方法有效,但是当前页面的URL更改为localhost:1337/ad/upload.我希望页面保持相同的网址.

This is my html form which accepts an image as file inout, the user can select an image file and then click submit. This works but the url of the current page changes to localhost:1337/ad/upload. I want the page to stay at the same url.

$("form#uploadForm").submit(function(event) {
    event.preventDefault();
    var formData = new FormData($(this)[0]);
    var posting = $.post(url, formData);

})

我已经尝试过使用jquery发送表单,但出现错误:未捕获的类型错误:非法调用

I have tried this to send the form using jquery but i get an error : Uncaught Type error : Illegal Invocation

当类型为multipart/formdata时,表单提交什么数据,我们如何在jQuery上获取这些数据

What data does the form submit when the type is multipart /formdata and how can we get this data on jQuery

推荐答案

processData

默认情况下,作为对象传递给data选项的数据(从技术上讲,不是字符串)将被处理并转换为查询字符串,以适合默认的内容类型"application/x-www-form" -urlencoded".如果要发送DOMDocument或其他未处理的数据,请将此选项设置为false.

By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

请检查 jQuery Ajax文档

尝试这样的ajax-

var form = new FormData($("#uploadForm")[0]);
$.ajax({
        url: your_url,
        method: "POST",
        dataType: 'json',
        data: form,
        processData: false,
        contentType: false,
        success: function(result){},
        error: function(er){}
});

这篇关于如何使用jQuery提交多部分表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆