gpt4 book ai didi

javascript - 如何在ajax请求中与formData一起发送附加数据

转载 作者:行者123 更新时间:2023-12-02 17:50:14 26 4
gpt4 key购买 nike

我有一个文件输入值的以下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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com