[英]How can I use jquery events to pass variables to php?
我有一个带有下拉菜单的表格,用于选择安排时间
我没有使用选择器输入,而是出于样式原因,使用了以下html来制作菜单。
<div class="tabs">
<div class="apt-time">
<h3>@Time</h3>
<ul class="time-list">
<li class="available">8:00am</li>
<li class="available">9:00am</li>
<li class="available">10:00am</li>
<li class="available">11:00am</li>
<li class="available">12:00am</li>
<li class="available">1:00pm</li>
<li class="available">2:00pm</li>
<li class="available">3:00pm</li>
<li class="available">4:00pm</li>
<li class="available">5:00pm</li>
</ul>
</div>
</div>
因此,我无法使用POST方法获取用户在菜单中单击的数据。 因此,我尝试提出一种解决方案,该解决方案可以使用以下代码中的GET方法将带有事件的字符串变量传递给我的php页面。 如果要使用if语句,则客户必须先单击菜单中的选项,然后才能提交表单。 有没有不使用选择器输入的方法吗?
$('.available').click(function() {
return clockTime = $(event.target).text()
})
$('.btn').click(function() {
if ($('.available').click) {
window.location.href = "textsms.php?"+clockTime
} else {
// warn client that they need to chose a time
}
})
您没有在重定向中定义get变量:
window.location.href = "textsms.php?"+clockTime
以下将“ clockTime”存储在$ _GET ['time']中
window.location.href = "textsms.php?time="+clockTime
编辑:无论如何,您的JS是不正确的。
var clockTime;
$('.available').click(function(e) {
clockTime = $(this).text();
})
$('.btn').click(function() {
if(typeof clockTime !== "undefined"){
window.location.href = "textsms.php?time="+clockTime
}else{
// warn client that they need to chose a time
}
});
您可以为此使用一个控制变量(还定义一个显示所选选项的css类):
var selectedTime = '';
$('.available').click(function() {
$('.available').removeClass('clicked');
$(this).addClass('clicked');
selectedTime = $(this).text();
})
$('.btn').click(function() {
if (selectedTime != '') {
window.location.href = "textsms.php?time="+selectedTime;
} else {
// warn client that they need to chose a time
}
})
您需要获取值并将其正确传递到您的位置:
$("ul.time-list").on("click","li.available",function(){
var selectedTime = $(this).text();
window.location.href = "textsms.php?varname="+selectedTime;
});
我喜欢使用jquery的on事件,因为只要您将外部静态元素作为目标,它就可以动态使用加载内容。
在下面添加了AJAX
功能。 该脚本将POST
值传递给名为textsms.php
PHP脚本,而无需刷新浏览器。
更新的代码:
<script>
$('.available').click(function() {
var clockTime = $(this).text();
$.ajax({
url:"textsms.php",
method:"POST",
data:{'clockTime':clockTime,var2:'2',}, // modify fields
success: function(data){
alert(data); // Do something with data received
},
});
});</script>
供测试用..
textsms.php:
<?php
print_r( $_POST );
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.