通過ajax post將文件與表單數據一起發送
2023-05-21
php問題
html5模板網
Sending file together with form data via ajax post(通過ajax post將文件與表單數據一起發送)
本文介紹了通過ajax post將文件與表單數據一起發送的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
我正在嘗試通過 ajax 上傳文件以及表單中的一些字段.但是,它不起作用.我收到此錯誤.
<塊引用>
未定義索引:-文件
這是我的代碼.
HTML
<div class="form-group"><label class="col-md-4 control-label" for="file">上傳軟件/文件</label><div class="col-md-4"><input id="file" name="file" class="input-file" type="file">
<div class="form-group"><label class="col-md-4 control-label" for="price">Price($)</label><div class="col-md-4"><input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required="">
Ajax
$("#add_product").click(function(e){e.preventDefault();product_name = $("product_name").val();//d = $("#add_new_product").serialize();$.ajax({類型:'POST',網址:'ajax.php',數據:$("#add_new_product").serialize(),成功:功能(響應){//警報(響應);}})});
PHP
if (0 <$_FILES['file']['error']){回聲:!";}別的{回聲ASa";}
我在這里遺漏了什么?
解決方案
你可以試試用 FormData()
:
$("form#files").submit(function(){var formData = new FormData($(this)[0]);$.ajax({網址:window.location.pathname,類型:'POST',數據:表單數據,異步:假,成功:功能(數據){警報(數據)},緩存:假,內容類型:假,過程數據:假});返回假;});
以上是示例代碼,但您可以使用它進行修改.
I'm trying to upload a file via ajax together with some fields in a form. However, it doesn't work. I get this error.
Undefined Index :- File
Here's my code.
HTML
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="file">Upload Software / File</label>
<div class="col-md-4">
<input id="file" name="file" class="input-file" type="file">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="price">Price($)</label>
<div class="col-md-4">
<input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required="">
</div>
</div>
Ajax
$("#add_product").click(function(e){
e.preventDefault();
product_name = $("product_name").val();
//d = $("#add_new_product").serialize();
$.ajax({
type: 'POST',
url: 'ajax.php',
data: $("#add_new_product").serialize(),
success: function(response)
{
//
alert(response);
}
})
});
PHP
if (0 < $_FILES['file']['error'])
{
echo ":!";
}
else
{
echo "ASa";
}
What am I missing here?
解決方案
Can you try using FormData()
:
$("form#files").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
The above is a sample code, but you may use it to modify it.
這篇關于通過ajax post將文件與表單數據一起發送的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!