作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个文件输入值的以下ajax请求onChange
。
$(':file').change(function(){
var file = this.files[0];
var formData = new FormData($('form')[0]);
var id= $(this).attr('data-post-id'); // What I want to send additionaly to file
$.ajax({
url: "http://localhost/bghitn/web/app_dev.php/image/upload",
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
return myXhr;
},
success: completeHandler,
data: formData,
data:{id:id}, // what is actually not working
cache: false,
contentType: false,
processData: false
});
});
我正在向 html 标记添加一个属性,其中包含我希望与文件相关数据一起发送的 id
。
<input type="file" name="img" data-post-id="{{entity.id}}" />
我在 Symfony2 下使用 PHP,例如:
if ($request->isMethod('POST')) {
$image = $request->files->get('img');
}
我需要一种等效的方法来获取 id。
最佳答案
通过url传递,
$(':file').change(function(){
var file = this.files[0];
var formData = new FormData($('form')[0]);
var id= $(this).attr('data-post-id'); // What I want to send additionnaly to file
$.ajax({
url: "http://localhost/bghitn/web/app_dev.php/image/upload?id="+id,
//...........................................................^....
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
return myXhr;
},
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
});
或者您可以使用append
方法添加id
$(':file').change(function(){
var file = this.files[0];
var formData = new FormData($('form')[0]);
formData.append("id",id);
//...............^.......
var id= $(this).attr('data-post-id'); // What I want to send additionnaly to file
$.ajax({
url: "http://localhost/bghitn/web/app_dev.php/image/upload?",
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
return myXhr;
},
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
});
关于javascript - 如何在ajax请求中与formData一起发送附加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21429384/
我是一名优秀的程序员,十分优秀!