在同一页面上,我有几种类型的代码: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 responseecho $response;?>AJAX(第三篇 - 页面底部)<script>function submitdata(){ var postcode = document.getElementById( "postcode" ); $.ajax({ type: 'post', data: { postcode:postcode }, // ??? });}</script>我必须在同一个文件中使用PHP,因为我正在使用woocommerce,并且我在尝试将文件放在外面时遇到很多错误现在我想知道如何在同一页面中使用所有这些
2 回答
慕丝7291255
TA贡献1859条经验 获得超6个赞
您需要将PHP放在脚本的开头。当它看到postcode参数时,它可以返回AJAX响应,然后exit不显示整页的HTML。
所以看起来应该是这样的:
<?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>
呼唤远方
TA贡献1856条经验 获得超11个赞
是的,您可以在同一页面上使用。
您错过了过程部分,例如:
success: function(){
// code where you present the results
}添加回答
举报
0/150
提交
取消
