如何在不重新加载页面的情况下将数据javascript传递到php页面
大家好,关于如何在不重新加载页面的情况下使用JavaScript将值传递给php,需要帮助。我想做的是,当我在文本框名称num1中放入一个值时,该值将转到available.php。。提前谢谢你。 这是我的密码 html代码如何在不重新加载页面的情况下将数据javascript传递到php页面,javascript,php,mysql,ajax,Javascript,Php,Mysql,Ajax,大家好,关于如何在不重新加载页面的情况下使用JavaScript将值传递给php,需要帮助。我想做的是,当我在文本框名称num1中放入一个值时,该值将转到available.php。。提前谢谢你。 这是我的密码 html代码 &时代; 设置可用学生 接近 javascript代码 <script type="text/javascript"> function availble_chair() { xmlhttp = new XMLHttpR
&时代;
设置可用学生
接近
javascript代码
<script type="text/javascript">
function availble_chair()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","available.php",false);
xmlhttp.send(null);
document.getElementById("count").innerHTML=xmlhttp.responseText;
}
availble_chair();
setInterval(function(){
availble_chair();
},1000);
</script>
功能可用的椅子()
{
xmlhttp=新的XMLHttpRequest();
open(“GET”,“available.php”,false);
xmlhttp.send(空);
document.getElementById(“count”).innerHTML=xmlhttp.responseText;
}
可用的椅子();
setInterval(函数(){
可用的椅子();
},1000);
下面是我的php代码available.php
<?php
$set = '';
$connection = mysqli_connect("localhost","root","","dbattendancelibrary");
$query=mysqli_query($connection,"SELECT COUNT(Time_in)-COUNT(Time_out) as Status FROM `tbl_student_form`");
$result = mysqli_fetch_array($query, MYSQLI_NUM);
if($result) {
if($result[0] <= $set) {
$availble = $set-$result[0];
echo "<p style='font-size:50px;margin-left:240px;'> " .$availble. "
</p>";
} else {
echo "<p class='alert alert-danger'>Library Already Full</p>";
}
}
?>
Javascript:
首先,在提交时需要一个事件侦听器,以便我们可以检测表单何时提交
// get a reference to your form
var form = document.getElementsByTagName('form');
// i suggest adding a classname or ID to your form if you have more then one form on the page
// if that is the case, then select the form by ID or class instead
// add event listener to the form
form.addEventListener('submit', function(event) {
// stop form submitting by default
event.preventDefault();
// get the value from the textbox, num1
var num1 = this.querySelector('#num1').value;
// send value of num1 to available.php via ajax
var xhr = new XMLHttpRequest();
xhr.open('GET', 'available.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
console.log("I worked!");
} else {
console.log("I didn't work!");
}
};
xhr.send(encodeURI('num1=' + num1));
}
PHP
要从AJAX请求中获取num1
值:
<?php
$num1 = isset($_GET['num1']) ? (int) trim($_GET['num1']) : 0;
if ($num1 > 0) {
// success
}
?>
我认为您应该使用Ajax。您可以在w3schools和TurtorialPoint上找到示例/教程。如果您有任何错误,请在此处指定,以便有人可以帮助解决。
<?php
$num1 = isset($_GET['num1']) ? (int) trim($_GET['num1']) : 0;
if ($num1 > 0) {
// success
}
?>