[英]Ajax Form Submission with Files
我有一個通過$ .post處理的表單,將數據發送到php腳本。 我的客戶只是要求我包括使用此表單(以及其他一些表單)上傳圖片的功能。
我已經搜索了大約一個小時,並且還沒有看到任何證據可以使用$.post()
真正做到這一點,所以我想伸出援手,看看是否有辦法做到這一點。
表單是這樣處理的:
jQuery( '.js-saveProduct' ).click(function(e) {
e.preventDefault();
acSaveProduct( jQuery(this).serializeArray() )
};
var acSaveProduct = function( form ) {
var _data = {
action: 'ac_save_product',
form: JSON.stringify( form )
}
jQuery.post(
ajaxscript.ajaxurl,
_data,
function( response ) {
// Do Stuff
}
);
};
如果在acSaveProduct()
console.log(form)
之后acSaveProduct()
console.log(form)
,則上載字段甚至不在要記錄的對象數組中。
我什至還沒有從PHP方面開始,因為我知道傳遞給PHP函數的form對象不包含我要查找的值。
編輯以顯示新嘗試
因此,嘗試使用@Andreas鏈接的技術時,我仍然遇到問題。 以下是我更新的jQuery / PHP代碼:
的HTML
<input type="file" name="acImageNew" id="acImageNew">
jQuery的
var acSaveProductAlt = function( form ) {
var file_data = jQuery( '#acImageNew' ).prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
jQuery.ajax({
url: the_ajax_script.ajaxurl,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
action: 'ac_ajax_save_product_alt',
success: function( response ) {
alert(JSON.parse(response.success));
}
});
};
的PHP
function ac_ajax_save_product_alt(){
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
$response = json_encode(
array(
'success' => true,
)
);
header( "Content-Type: application/json" );
echo $response;
exit;
}
最后,我得到一個警報,警報的內容為0
。 我究竟做錯了什么?
首先嘗試JSON解析響應,然后訪問success
密鑰。
jQuery.ajax({
url: the_ajax_script.ajaxurl,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
action: 'ac_ajax_save_product_alt',
success: function( response ) {
alert(JSON.parse(response).success);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.