在同一頁(yè)面上,我有幾種類(lèi)型的代碼:PHP,JS和HTML。我想從HTML表單中獲取信息并進(jìn)行PHP處理,而無(wú)需在單擊“發(fā)送”按鈕后重新加載頁(yè)面。PHP獲取它通過(guò)API發(fā)送的值(來(lái)自表單),并在頁(yè)面上顯示API響應(yīng)HTML(首頁(yè))<form method="post"> <input class="display-inline form-postcode" type="text" name="postcode" id="postcode" placeholder="Add your postcode for delivery estimate"> <input class="form-postcode-submit" type="submit" value="Get estimate!"></form>PHP(第二個(gè))<?php if(isset($_POST['postcode'])) { $toPostcode = $_POST['postcode'];}// do stuff with $toPostcode// use the API// get responseecho $response;?>AJAX(第三篇 - 頁(yè)面底部)<script>function submitdata(){ var postcode = document.getElementById( "postcode" ); $.ajax({ type: 'post', data: { postcode:postcode }, // ??? });}</script>我必須在同一個(gè)文件中使用PHP,因?yàn)槲艺谑褂脀oocommerce,并且我在嘗試將文件放在外面時(shí)遇到很多錯(cuò)誤現(xiàn)在我想知道如何在同一頁(yè)面中使用所有這些
2 回答

慕絲7291255
TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
您需要將PHP放在腳本的開(kāi)頭。當(dāng)它看到postcode
參數(shù)時(shí),它可以返回AJAX響應(yīng),然后exit
不顯示整頁(yè)的HTML。
所以看起來(lái)應(yīng)該是這樣的:
<?phpif(isset($_POST['postcode'])) { $toPostcode = $_POST['postcode']; // do stuff with $toPostcode // use the API // get response echo $response; exit;}?><html><head> ...</head><body> ... <form method="post"> <input class="display-inline form-postcode" type="text" name="postcode" id="postcode" placeholder="Add your postcode for delivery estimate"> <input class="form-postcode-submit" type="submit" value="Get estimate!"> </form> ... <script> function submitdata() { var postcode = document.getElementById( "postcode" ); $.ajax({ type: 'post', data: { postcode:postcode }, // ??? }); } </script></body></html>

呼喚遠(yuǎn)方
TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超11個(gè)贊
是的,您可以在同一頁(yè)面上使用。
您錯(cuò)過(guò)了過(guò)程部分,例如:
success: function(){ // code where you present the results }
添加回答
舉報(bào)
0/150
提交
取消