[英]prevent redirect to php file after form submit
在研究了多個小時之后,我終於決定自己發布問題,因為對別人有用的東西似乎對我沒用。 請記住,我對ajax和jquery還是比較陌生,但是由於我正處於當前項目的最后期限,所以我沒有時間進行全部研究。
我有以下HTML表單:
<div class="form">
<form id="savePlacemarkForm" method="post" action="createPlacemark.php">
<div>
<input type="text" id="placemarkName" name="placemarkName" placeholder="Name:"/>
</div>
<div>
<input type="text" id="placemarkAddress" name="placemarkAddress" placeholder="Adress:"/>
</div>
<div>
<input type="text" id="placemarkTag" name="placemarkTag" placeholder="Tags:"/>
</div>
<div>
<textarea id="placemarkDescription" name="placemarkDescription" placeholder="Description" rows="1" cols="1"></textarea>
</div>
<div>
<input id="latitude" type="text" name="latitude"/>
</div>
<div>
<input id="longtitude" type="text" name="longtitude"/>
</div>
<button class="md-close" id="savePlacemark" onclick="createPlacemark();"/>Save</button>
</form>
<button class="md-close">Cancel</button>
<script src="my_script.js" type="text/javascript"></script>
</div>
如您所見,我將動作設置為createPlacemark.php,該動作將從這些字段中獲取輸入並將其保存到我的數據庫中,效果很好! 但是,由於這應該工作而無需重定向或重新提交頁面,因此意味着ajax! 我包含如下所示的my_script.js:
$("#savePlacemark").click( function() {
$.post( $("#savePlacemarkForm").attr("action"),
$("#savePlacemarkForm :input").serializeArray();
});
clearInput();
});
$("#savePlacemarkForm").submit( function() {
return false;
});
function clearInput() {
$("#savePlacemarkForm :input").each( function() {
$(this).val('');
});
}
如您所見,該帖子對我來說是有效的,但是由於某種原因,返回false; 似乎不為我工作,因為我不斷重定向到前面提到的php文件。
任何幫助將不勝感激! 謝謝!
嘗試以下方法。 .submit()
函數實際上觸發了表單的提交。 從腳本中刪除它,因為當您已經用$.post
發布值時就不需要它了。
$("#savePlacemark").click( function() {
$.post( $("#savePlacemarkForm").attr("action"),
$("#savePlacemarkForm :input").serializeArray();
});
clearInput();
});
function clearInput() {
$("#savePlacemarkForm :input").each( function() {
$(this).val('');
});
}
嘗試這個
<button onclick="return createPlacemark();">Save</button>
它可能會幫助您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.