猿问

在同一页面中使用PHP和AJAX的最佳方法

在同一页面上,我有几种类型的代码:PHP,JS和HTML。我想从HTML表单中获取信息并进行PHP处理,而无需在单击“发送”按钮后重新加载页面。


PHP获取它通过API发送的值(来自表单),并在页面上显示API响应


HTML(首页)


<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(第二个)


<?php

    if(isset($_POST['postcode'])) {

     $toPostcode = $_POST['postcode'];

}


// do stuff with $toPostcode

// use the API

// get response


echo $response;

?>

AJAX(第三篇 - 页面底部)


<script>


function submitdata()

{

 var postcode = document.getElementById( "postcode" );


 $.ajax({

 type: 'post',

 data: {

 postcode:postcode

 },


  // ???


 });

}

</script>

我必须在同一个文件中使用PHP,因为我正在使用woocommerce,并且我在尝试将文件放在外面时遇到很多错误


现在我想知道如何在同一页面中使用所有这些


翻阅古今
浏览 688回答 2
2回答

慕丝7291255

您需要将PHP放在脚本的开头。当它看到postcode参数时,它可以返回AJAX响应,然后exit不显示整页的HTML。所以看起来应该是这样的:<?phpif(isset($_POST['postcode']))&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$toPostcode&nbsp;=&nbsp;$_POST['postcode']; &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;do&nbsp;stuff&nbsp;with&nbsp;$toPostcode &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;use&nbsp;the&nbsp;API &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;get&nbsp;response &nbsp;&nbsp;&nbsp;&nbsp;echo&nbsp;$response; &nbsp;&nbsp;&nbsp;&nbsp;exit;}?><html><head> &nbsp;&nbsp;&nbsp;&nbsp;...</head><body> &nbsp;&nbsp;&nbsp;&nbsp;... &nbsp;&nbsp;&nbsp;&nbsp;<form&nbsp;method="post"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input&nbsp;class="display-inline&nbsp;form-postcode"&nbsp;type="text"&nbsp;name="postcode"&nbsp;id="postcode"&nbsp;placeholder="Add&nbsp;your&nbsp;postcode&nbsp;for&nbsp;delivery &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;estimate"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input&nbsp;class="form-postcode-submit"&nbsp;type="submit"&nbsp;value="Get&nbsp;estimate!"> &nbsp;&nbsp;&nbsp;&nbsp;</form> &nbsp;&nbsp;&nbsp;&nbsp;... &nbsp;&nbsp;&nbsp;&nbsp;<script> &nbsp;&nbsp;&nbsp;&nbsp;function&nbsp;submitdata() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;postcode&nbsp;=&nbsp;document.getElementById(&nbsp;"postcode"&nbsp;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$.ajax({ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;type:&nbsp;'post', &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;data:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;postcode:postcode &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;??? &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;</script></body></html>

呼唤远方

是的,您可以在同一页面上使用。您错过了过程部分,例如:success:&nbsp;function(){ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;code&nbsp;where&nbsp;you&nbsp;present&nbsp;the&nbsp;results &nbsp;&nbsp;&nbsp;&nbsp;}
随时随地看视频慕课网APP

相关分类

Java
我要回答