使用jquery ajax在同一请求中上传文件和JSON数据? [英] Uploading files and JSON data in the same request with jquery ajax?
本文介绍了使用jquery ajax在同一请求中上传文件和JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将图片文件上传到画布。假设画布已经有对象,那么我必须先抓住json,上传图像,然后重新加载页面。问题是,我不能将上传的图像文件与json数据一起发送到同一个ajax请求中。这是我的代码:
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:
<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');
});
虽然我得到的json数据很好,但表单数据只是空的。还有其他更好的解决方案吗?
Whilst I get the json data just fine, the form data are just empty. Is there any other better solution?
推荐答案
删除
var dataString = JSON.stringify(data.serializeObject());
,它已经是Json,
和尝试设置ajax属性:
and try to set ajax properties:
processData: false,
contentType: false,
这篇关于使用jquery ajax在同一请求中上传文件和JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文