javascript 使用 jquery ajax 在同一个请求中上传文件和 JSON 数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30655582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:30:04  来源:igfitidea点击:

Uploading files and JSON data in the same request with jquery ajax?

javascriptjqueryajaxjson

提问by user1576748

I need to upload image file to canvas. Assuming the canvas already has objects, then I have to grab the json first, upload the image, and reload the page. The problem is, I can't send the uploaded image file together with json data in the same ajax request. Here is my code:

我需要将图像文件上传到画布。假设画布已经有对象,那么我必须先抓取json,上传图像,然后重新加载页面。问题是,我无法在同一个 ajax 请求中将上传的图像文件与 json 数据一起发送。这是我的代码:

<canvas id="canvas"></canvas>
<form enctype="multipart/form-data" id="myform" method="post" action="">
<input type="file" name="image" id="image" />
... (other input tags)
<button type="submit" id="upload">Upload</button>
</form>

$('#upload').bind("click",function(event) {
    event.preventDefault();
    var json = JSON.stringify(canvas.toDatalessObject());
    var url = "upload.php";
    var data = new FormData($('#myform')[0]);
    var dataString = JSON.stringify(data.serializeObject());
    $.post(url, { json: json, data: dataString }, 'json');  
});

Whilst I get the json data just fine, the form data are just empty. Is there any other better solution?

虽然我得到的 json 数据很好,但表单数据只是空的。有没有其他更好的解决方案?

回答by Kevin Simple

remove

消除

var dataString = JSON.stringify(data.serializeObject());

,it's already Json,

, 已经是 Json,

and try to set ajax properties:

并尝试设置 ajax 属性:

    processData: false,
    contentType: false,