将JQuery变量传递给php


Pass JQuery variables to php

我想传递jQuery变量到php文件,这是my_js.js文件

  function updates() {
         $.getJSON("php/fetch.php", function(data) {
           $.each(data.result, function(){
            var s_id = this['sender_id'];        
           });
     });
    }

我想把它显示在PHP文件中

<html>
<head><title>Pass jquery var to php file</title>
</head>
<body>
<div> <?php echo $s_id ; ?> </div>
<script type="text/javascript" src="my_js.js"></script>
<script type="text/javascript" src="jquery.js"></script>
</body>
</html>

您可以考虑使用jQuery来设置页面中的s_id值。

你可以这样修改你的HTML(重要的部分是添加的span元素):

<html>
    <head><title>Pass jquery var to php file</title>
    </head>
    <body>
        <div><span id="s_id"></span></div>
        <script type="text/javascript" src="my_js.js"></script>
        <script type="text/javascript" src="jquery.js"></script>
    </body>
</html>

您可以在getJSON回调中使用jQuery设置值,如下所示,以查找添加的span元素并修改其文本:

function updates() {
     $.getJSON("php/fetch.php", function(data) {
       $.each(data.result, function(){
        $("#s_id").text(this['sender_id']);        
       });
 });
}