javascript 如何在php代码中使用jQuery变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24496612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use jQuery variable inside php code?
提问by M1M6
I have PHP code inside jQuery scriptm, and I want to pass a jQuery variable to PHP.
我在 jQuery scriptm 中有 PHP 代码,我想将一个 jQuery 变量传递给 PHP。
This is my code :
这是我的代码:
$(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);
});
});
});
I want the value of id to be exist in php code ($query
)
我希望 id 的值存在于 php 代码中 ( $query
)
回答by What have you tried
Use $.post
:
使用$.post
:
$(this).on('click', function(e){
e.preventDefault();
var Id = $(this).attr('id');
$.post("yourscript.php", {
Id: Id
}, function(data){
var theResult = data;
}, 'json' );
});
This is going to send two parameters (param1
and param2
to a php script called yourscript.php
. You can then use PHP to retrieve the values:
这将发送两个参数 (param1
和param2
一个名为 的 php 脚本yourscript.php
。然后您可以使用 PHP 来检索值:
$Id= isset($_POST['Id']) ? $_POST['Id'] : '';
The idea is you're sending variables from the client side to the server side via Ajax.
这个想法是您通过 Ajax 从客户端向服务器端发送变量。
Yourscript.php
你的脚本.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;
?>