[英]How to put the ajax response/result into variable php
我可以将ajax响应放入变量中吗? 这样我就可以将变量回显到php中了?
ajax.php
<script>
function random_no(){
$.ajax({
url: "test.php",
success: function(result){
$("#random_no_container").html(result);//the result was displayed on this div
}
});
}
</script>
在上面的示例代码中,我从test.php调用查询结果,结果显示在div上,但我想将其放在变量上并回显该变量。 类似于下面的代码
<?php echo $variable;?>
这样可以吗? 请帮我。 非常感谢。
您无法从客户端在服务器和Ajax上执行PHP,因此无法为PHP变量分配ajax响应。 在客户端上渲染了PHP之后,它就是HTML,没有PHP代码。
function random_no(){
$.ajax({
url: "test.php",
success: function(result){
var result_val=result;
alert(result);
}
});
}
正如@dev回答的那样,您需要以不同的方式执行服务器和客户端代码! 我在这里仅回答了您需要的变量。但是在开发网站时,不应在php标签<?php ?>
使用javascript
<div id="random_no_container">
<?php
if(isset($_GET['variable'])) {
$variable = $_GET['variable'];
echo $variable;
} else {
echo "<script>sessionStorage.setItem('stopped',0);</script>";
}
?>
</div>
<script>
var stopped = sessionStorage.getItem("stopped");
if(stopped == 0) {
random_no();
}
function random_no(){
$.ajax({
url: "test.php",
success: function(result){
sessionStorage.setItem("stopped",1);
//$("#random_no_container").html(result);//the result was displayed on this div
location.href = "ajax.php?variable="+result;
}
});
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.