2 回答

TA貢獻1798條經驗 獲得超3個贊
問題是因為您正確聲明了一個FormData對象,但隨后在下一行中立即用字符串覆蓋它。
您需要將append() 所有數據添加到 FormData 對象中。此外,您需要向append()方法提供文件數據,而不是引用控件的 jQuery 對象input type="file"。
var form_data = new FormData();
form_data.append('msg_area_cst', msg_area_cst);
form_data.append('num_cst', num_cst);
form_data.append('upload', $('input[name=upload]')[0].files[0]);
話雖這么說,如果您從中讀取值的控件包含在元素中,則可以使事情變得更加簡單form。然后您可以使用submit該表單的事件并將對其的引用傳遞給 FormData 構造函數。
confirm()另外,您也不會對單擊“我假設您想停止表單提交”的結果執行任何操作Cancel,上面的示例現在使用preventDefault().
最后,使用起來html == 1很不可靠。首先html是一個字符串,因此依賴于整數的隱式類型強制并不理想。此外,如果包含任何空格,返回純文本響應可能會導致問題。我強烈建議您更改服務器端邏輯以返回序列化格式(例如 JSON),并使用布爾值作為“成功”標志。
話雖如此,試試這個:
$('#yourForm').on('submit', function(e) {
if (!confirm("Do you really want to send messages?")) {
e.preventDefault();
}
$('.loading').html(loader).fadeIn();
$.ajax({
url: "../server/CustomMsg.php",
type: "POST",
data: new FormData(this),
success: function(html) {
if (html.trim() === "1") {
$('#register_form').fadeOut('slow');
$('.loading').fadeOut();
$('.message').html('Successfully Sent ! ').fadeIn('slow');
} else
alert('Sorry, unexpected error. Please try again later.');
}
}
});
});

TA貢獻1884條經驗 獲得超4個贊
試試這個ajax代碼
$.ajax({
url: "../server/CustomMsg.php",
type: "POST",
data: form_data,
contentType: false,
cache: false,
processData:false,
async: true,
success: function(html) {
if (html == 1) {
$('#register_form').fadeOut('slow');
$('.loading').fadeOut();
$('.message').html('Successfully Sent ! ').fadeIn('slow');
} else
alert('Sorry, unexpected error. Please try again later.');
}
});
- 2 回答
- 0 關注
- 173 瀏覽
添加回答
舉報