[英]jquery ajax request not returning to page
我的表單將多個文本字段和一個文件上載到php腳本,以保存文件並將文本字段保存到sql db。 那正在工作,我的PHP腳本以
('state' => 200, "success" => true, "id" => $_POST['id'], "titlea" => $_POST['title'], "addressa" => $_POST['address'], "lot_sizea" => $_POST['lot_size'], "zoninga" => $_POST['zoning'], "build_sizea" => $_POST['build_size'], "sale_pricea" => $_POST['sale_price'], "lease_pricea" => $_POST['lease_price'], "commenta" => $_POST['comment'], "transactiona" => $_POST['transaction'], "ad_linka" => $ad_link,
);
exit(json_encode($response));
這將返回json編碼的響應。 但是,返回值停留在php頁面上,而不是返回帶有ajax請求的頁面。 這是我的ajax腳本:
$("document").ready(function() {
$(".data-form").submit(function() {
var formData = new FormData($('form')[0]);
if (confirm("\t\t\tAre you ready to sumbmit this listing?\nYou can always edit the listing after going to the menu tab - edit listing.")) {
$.ajax({
type: "POST",
dataType: "json",
url: "add-list.php",
data: formData,
success: function(response) {
if (response.success) {
$("#modal1").modal('hide');
$("#add_frame").show();
$("#newbutt").show();
$(".atitle").html('<a href="' + response.ad_linka + '" target="_blank">' + response.titlea + '</a>');
$(".acomment").html(response.commenta);
$(".aaddress").html(response.addressa);
$(".asale-price").html(response.sale_pricea);
$(".alease-price").html(response.lease_pricea);
$(".alot-size").html(response.lot_sizea);
$(".abuilding-size").html(response.build_sizea);
$(".azoning").html(response.zoninga);
} else {
console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
}
},
error: function() {
alert("An Error has ocurred contacting the server. Please contact your system administrator");
}
});
return false;
}
});
});
如何更改此設置,以便可以返回頁面並允許成功方法運行?
這是我表格的開頭:
<form class="avatar-form" enctype="multipart/form-data" method="POST">
幾個問題:
首先,您需要確保選擇正確的表格。 $('form')
將選擇所有形式,而$('form')[0]
將選擇第一個形式。 相反,您應該定位正確的表格。
$('.data-form')[0]
接下來,在發送FormData時,必須將processData和contentType設置為false,以便jQuery不會嘗試處理FormData。 (這是在$.ajax({...})
)
contentType: false,
processData: false
注意:Ajax文件上傳在IE <10上不起作用
這也是一個好習慣(至少在調試時),使用event.preventDefault
而不是返回false,並在處理程序的頂部進行操作,這樣,如果發生語法錯誤,您的表單將無法提交看到錯誤。 有關示例,請參見Preston S的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.