gpt4 book ai didi

javascript - 使用ajax根据输入显示表单

转载 作者:行者123 更新时间:2023-11-27 23:17:55 24 4
gpt4 key购买 nike

我使用 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 运行,这样我就不需要提交页面等...我不想刷新页面 - 我只想交换内容。

最佳答案

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'));
}

关于javascript - 使用ajax根据输入显示表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35655051/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com