我正在使用 jQuery 的 ajax 编写一个练习网站。 目前我有 3 个按钮,每个按钮在单击时都会使用 ajax 调用以表单显示不同的内容。内容存储在不同的文件中。假设您在单击第一个按钮后显示的内容中的表单中输入“AAA”。然后单击第二个按钮,这会将第一个内容替换为新的第二个内容。然后您在此处的表格中输入“BBB”。我想要实现的是,当你这样做时,我不希望页面忘记你在第一页中输入的内容(或者在使用ajax调用更改页面之前),最后,你按提交按钮,这在所有按钮的内容中都很常见。然后,我希望网页同时提交“AAA”和“BBB”以进行更多计算。
这可能吗? 这有点像披萨网站。假设网站上有 2 个选项卡,一个用于披萨面团选项,另一个用于配料选项。还假设选项卡的分页是使用 ajax 通过异步显示内容进行的。当您在披萨面团选项卡中选择选项时,您更改选项卡以选择配料选项。然后您最终下订单,这反射(reflect)了顾客对面团和配料的选择。
你怎么可能实现这个?任何建议将不胜感激。
我需要使用 SQL 的数据库吗?由于这是一个简单的练习网站,因此一旦您提交表单并且客户关闭页面,它就不必记住客户的选项。
这是我的代码的一部分,因为我无法全部编写。我还省略了一些不重要的部分。
php 文件 1:
<script>
$(document).ready(function(){
$(".dough, .topping").click(function(){
$.ajax({
url: /*URL is either dough.php or topping.php*/
success: function(data){
$(".result").html(data);
},
error: function(data){
alert("error");
}
});
});
});
</script>
<button class="dough">Dough</button>
<button class="topping">Toppings</button>
<div class="result"></div> <!--Here I want to show the content with ajax-->
php file2 (=dough.php) 和 file3(=topping.php):/*这是包含表单的文件,两者具有相同的结构 */
<form action="confirm.php" method="POST">
<!--Pizza's dough and topping photos, price and name etc-->
<input type="text" name="******"> <!--This is the input form-->
</form>
在这种情况下,我觉得我应该在表单标记之外添加最终的“提交”按钮,因为提交按钮很常见,并且在分页过程中应该保留在页面底部。
最佳答案
<form action="confirm.php" method="POST">
<!--Pizza's dough and topping photos, price and name etc-->
<input type="text" class='myValue' name="******">
<!-- this button is for saving the input entered above; for topping form give 'toppings' class-->
<input class='option-button pizza-dough' type='button' value='select'/>
</form>
为上述表单添加事件处理程序
$('.result').on('click','.pizza-dough,.toppings',function(e){
//using on() because forms are dynamically added
var myValue = $(this).siblings('.myValue').val();
if(this).hasClass('.pizza-dough') {
localStorage.setItem('pizza-dough', myValue);//store the value in localStorage
}else{
localStorage.setItem('toppings', myValue);//store the value in localStorage
}
});
现在,假设您有以下常见的提交按钮
<input type='button' value='submit' class='submit-values'/>
为此按钮添加事件处理程序以提交值
$('.submit-values').click(function(e){
var dataToSend = {'pizza-dough':localStorage.getItem('pizza-dough'),'topppings':localStorage.getItem('toppings')};
$.ajax({
url: /*submit url*/,
method: "POST",
data: dataToSend,
success: function(data){
//handle success
},
error: function(data){
//handle error
}
});
});
为 localStorage 值添加验证由您完成。 了解更多关于 localStorage和 sessionStorage选择最适合您的。
关于javascript - 使用Ajax进行页面更改,仍然保存输入的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41392056/