如何在php代码中使用jQuery变量

How to use jQuery variable inside php code?

本文关键字:jQuery 变量 代码 php      更新时间:2023-09-26

我在jQuery script中有PHP代码,我想传递一个jQuery变量给PHP。

这是我的代码:

$(document).ready(function() {
 $('.editclass').each(function() {
  $(this).click(function(){
    var Id = $(this).attr('id');
      <?php 
            include "config.php";
            $query="SELECT * FROM users WHERE UserId=''id''";
      ?>
 $("#user_name").val(Id);
   });
});
});

我希望id的值存在于php代码($query)

使用$.post:

$(this).on('click', function(e){
    e.preventDefault();
    var Id = $(this).attr('id');
    $.post("yourscript.php", { 
        Id: Id 
    }, function(data){
        var theResult = data;
}, 'json' );
});

这将发送两个参数(param1param2)到一个名为yourscript.php的php脚本。然后可以使用PHP检索值:

$Id= isset($_POST['Id']) ? $_POST['Id'] : '';

这个想法是你通过Ajax将变量从客户端发送到服务器端。

Yourscript.php

 <?php 
     include "config.php";
     $query="SELECT * FROM users WHERE UserId=$Id";
    /* Get query results */
    $results = use_mysql_method_here();
    /* Send back to client */
    echo json_encode($results);
    exit;    
 ?>