简体   繁体   English

如何在同一页面中将ajax成功结果值设置为PHP变量

[英]How to set the ajax success result value to PHP variable in same page

 function submitID(){

 // some codes working in here....

var text="A_1";                 
var name="test";

$.ajax({
    url: 'callmethod.php',
    type: 'post',
    data: {'action':'methodname', 'text': text, 'name':name},
            success: function(data, status) {
            var results = JSON.parse(data);

            for(var i = 0; i < results.length; i++){
                var id= results[i]['ID'];
                alert(id);  --- I got the value of ID in here -- example output value : Hello                                                                       
            }
        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });
}

What I would like to do in here, I got the value of var id but I want to set as the PHP variable $valuephp= >>> id <<< how can I do for that?我想在这里做什么,我得到了 var id 的值,但我想设置为 PHP 变量 $valuephp= >>> id <<< 我该怎么做? please help me to advice.请帮我指教。

In short, its not possible, like that to set ajax response to php variable because 简而言之,这是不可能的,像那样将ajax响应设置为php变量,因为

PHP runs - Server Side before page load and builds the page PHP运行-服务器端在页面加载和构建页面之前
JS (and thus AJAX) runs - Client Side AFTER the server gave your browser the page JS(以及AJAX)运行-服务器在客户端为浏览器提供页面后

So what you can do ? 那你能做什么?

  • You post data to your server with your ajax call, so in server side, you can set php variable.You can store this in a session variable if you need it later, or in the database. 您可以通过ajax调用将数据发布到服务器,因此在服务器端可以设置php变量。如果以后需要,可以将其存储在会话变量中,也可以存储在数据库中。

You can store ajax result in php variable by embedding ajax result div into php tag. 您可以通过将ajax结果div嵌入到php标签中来将ajax结果存储在php变量中。

Assign ajax response variable to js variable and then just assign it to your html div containing php variable as: 将ajax响应变量分配给js变量,然后将其分配给包含php变量的html div,如下所示:

$('#result').text('test');


<?php
 $result='<div id="result"></div>';
// Here you embed div in php tag and store in php varible
?>

In your ajax call, after success or error 在您的ajax调用中,成功或错误之后

<?php   $variablephp = "<script>document.write(111)</script>"   ?> 

Now you can access that variable, make sure that variable actually used after ajax call 现在您可以访问该变量,请确保在ajax调用之后实际使用了该变量

<?php echo $variablephp; ?>

不可能,但是您需要技巧,简单的技巧是用PHP标签编码JS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM