将 javascript 变量传递给 PHP 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10084689/
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
Passing javascript variable to PHP function
提问by alkhader
I have this javascript code
我有这个 javascript 代码
<Script>
function getGroupId(){
var group=document.getElementById("selectedOptions").value;
var groupFirstLetter=group.substring(2);
}
</Script>
I need to pass the groupFirstLetter
to a PHP function which will count how many users in this group and return the value to the javascript function.
我需要将 传递groupFirstLetter
给一个 PHP 函数,该函数将计算该组中有多少用户并将该值返回给 javascript 函数。
Any ideas please?
请问有什么想法吗?
Thanks,
谢谢,
回答by Songo
You can use jQuery for that to post an AJAX request. See this example taken out of jQuery documentation:
您可以使用 jQuery 来发布 AJAX 请求。请参阅从 jQuery 文档中提取的此示例:
$.ajax({
type: "POST",
url: "some.php",
data: {groupFirstLetter:groupFirstLetter},
complete: function(data){
//data contains the response from the php file.
//u can pass it here to the javascript function
}
});
The variable will be available in your PHP code as $_POST['groupFirstLetter']
.
You can manipulate it as you wish then echo
a response to the browser again and it will be available in the data
variable.
references:
该变量将在您的 PHP 代码中以$_POST['groupFirstLetter']
. 您可以随意操作它,然后echo
再次响应浏览器,它将在data
变量中可用。参考:
回答by ab_dev86
As javascript runs on user's browser you have to do an http request to a php page. POST or GET can be used to send parameters.
当 javascript 在用户的浏览器上运行时,您必须向 php 页面发出 http 请求。POST 或 GET 可用于发送参数。
To make a http call with javascript refer to this: HTTP GET request in JavaScript?
要使用 javascript 进行 http 调用,请参考:JavaScript 中的 HTTP GET 请求?
回答by Gustav
Use jQuery (jquery.com).
使用 jQuery (jquery.com)。
Dynamically load the php-file sending the variable using ajax like so:
使用 ajax 动态加载发送变量的 php 文件,如下所示:
$.post("file.php", {variable_name: value}, function(returned_data){
console.log(returned_data); //or do whatever you like with the variable
});
and your php-file will access the variable as:
并且您的 php 文件将访问该变量:
$_POST['variable_name'];