![](/img/trans.png)
[英]how to change the variable of php with javascript button click without reloading the page
[英]How to get javascript value into php variable without reloading the page using ajax
在这里,我想在不使用任何 POST 或 GET 方法的情况下从JavaScript获取一个值到PHP变量。
这里我给出了 HTML 代码:
<input type="number" name="days" id="days" class="col-sm-2 form-control" placeholder="DAYS">
<input type="number" name="night" id="night" class="col-sm-2 form-control" placeholder="NIGHT">
<button id="generate" onclick="GetValue()" class="btn btn-danger">Generate</button>
Javascript代码
<script>
$(function(){
$("#generate").on('click', function(){
var days = $("#days").val();
var night=$("#night").val();
var base_url = $('#base').val();
$.ajax({
type: 'post',
url: base_url,
data: {'days' : days, 'night': night},
success: function( data ) {
console.log(data);
}
});
});
});
</script>
代码
<?php
$days = $_POST['days'];
$night = $_POST['night'];
echo $days . " " . $night;
?>
变量值不起作用。
您不能直接将 javascript 变量分配给 PHP 变量,这就是使用 ajax 的原因。
如果您想在不刷新页面并使用相同页面的情况下对服务器端的客户端变量执行操作,那么您必须在客户端开始之前在页面顶部编写 PHP 代码,然后使用 exit 中断PHP 响应完成。 并且在 jquery ajax 中忘记 URL 部分,因为您使用相同的页面进行请求和响应。
注意:确保包含 jQuery
覆盖表单标签中的所有元素,因此我们可以使用序列化方法简单地发送数据。
索引.php
<?php
if(isset($_POST) && !empty($_POST['days'])){
$days = $_POST['days']; // you can write the variable name same as input in form element.
$night = $_POST['night'];
//Perform any operations on this variable and send in response whatever you want it will send the response to success function of jquery ajax and you can check response in `data`
echo $days . " " . $night;
exit();
}
?>
<!--<form id='frmsbmt' method='post' action='#'>-->
<input type="number" name="days" id="days" class="col-sm-2 form-control" placeholder="DAYS">
<input type="number" name="night" id="night" class="col-sm-2 form-control" placeholder="NIGHT">
<button id="generate" class="btn btn-danger">Generate</button>
<!--</form>-->
<script>
$(function(){
$("#generate").on('click', function(){
var days = $("#days").val();
var night=$("#night").val();
var base_url = $("#base").val();
$.ajax({
type: 'post',
//url: base_url,
data: {'days' : days, 'night': night}, //$("#frmsbmt").serialize(), //form serialize will send all the data to the server side in json formate, so there is no need to send data seperately.
success: function( data ) {
console.log(data);
//alert(data);
// It will write the response in developer tools console tab or you can alert it.
}
});
});
});
</script>
您可以为此使用 AJAX 调用。
function GetValue() {
var str = document.getElementById('days').value;
$.ajax({
type: 'post',
url: 'text.php',
data: {
someValue: str
},
success: function( data ) {
console.log( data );
}
});
}
在不使用任何 post 或 get 方法来检索变量的情况下回答您的问题是不可能的。 一种语言是服务器端语言,一种语言是客户端语言,如果这两种语言从不通过既定标准进行通信,那么在两者之间传递变量的协议是不可能的。 PHP 被翻译成服务器端,这意味着客户端接口并不真正知道它的存在,除非有一个与方法相关的操作,即 get 或 post。 Ajax 请求使用 POST 或 GET 或其他已建立的方法之一进行通信。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.