我使用wordpress设计了一个网站, - 在我的网站上,我想显示一个按邮政编码组织的预订系统(所以我在不同的日子里待在同一个区域)。
我写了一些PHP代码,允许我输入一个邮政编码,然后删除任何空格并删除最后3个字符。剩下的是根据邮政编码列表检查的,根据邮政编码的不同,它会显示不同的表格......
这是代码:
<?php
$postcode = $_POST['postcode'];
$postcode = preg_replace('/\s+/', '', $postcode);
$postcode = substr($postcode, 0, -3);
if(in_array($postcode, array("NR1", "NR2", "NR3", "NR4", "NR5", "NR6", "NR7", "NR8", "NR9", "NR19", "NR20"))){
?>
[bookly-form staff_member_id="2" hide="staff_members,date,week_days,time_range"]
<?php
} elseif(in_array($postcode, array("NR10", "NR11", "NR12", "NR26", "NR27", "NR28"))) {
?>
[bookly-form staff_member_id="3" hide="staff_members,date,week_days,time_range"]
<?php
} elseif(in_array($postcode, array("NR13", "NR14", "NR15", "NR29", "NR30", "NR31", "NR32", "NR33", "NR34", "NR35", "IP18", "IP19", "IP20", "IP21", "IP22"))) {
?>
[bookly-form staff_member_id="4" hide="staff_members,date,week_days,time_range"]
<?php
} else {
?>
Thank you for enquiring about our microchipping services. Unfortunatly we don't cover your postcode at the moment.
If you'd like to know when we do cover your area simply fill out the form below or feel free to call our offices to register your details
[ccf_form id="57"]
<?php
}
?>
考虑到这是在wordpress中,我可以使用一个php插件来调用代码等,并在html中手动编写表单 - 但是如何让它通过ajax运行,这样我就不需要提交页面等了...我不希望页面刷新 - 我只想让内容交换。
答案 0 :(得分:1)
html文件中邮政编码的初始表格:
<form id="form" action="" method="post">
<input type="text" id="postcode" name="postcode" value="" />
<button type="submit">Submit</button>
</form>;
<div id="return-wrap"></div>
提交序列化数据以进行发送。 (console.log();用于调试,您可以在浏览器控制台中看到结果)
jQuery(document).ready(function ($) {
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: $(this).serialize(),
dataType: 'json',
beforeSend: function () {
},
success: function (data, textStatus, xhr) {
console.log(data);
console.log(data.status);
$('#return-wrap').html(data.result);
},
error: function (xhr, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
console.log(data.status);
}
});
});
});
然后在php中访问数据,就像访问任何其他帖子数据一样
if($_POST){
$template = $_POST['postcode'];
/** Do whatever with this data */
$form = '';
echo json_encode(array('status' => 'ok', 'result' => $form));
} else {
echo json_encode(array('status' => 'error'));
}