简体   繁体   English

将 javascript 变量传递给 PHP function

[英]Passing javascript variable to PHP function

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 function,这将计算该组中有多少用户并将值返回给 javascript function。

Any ideas please?有什么想法吗?

Thanks,谢谢,

You can use jQuery for that to post an AJAX request.您可以使用 jQuery 来发布 AJAX 请求。 See this example taken out of jQuery documentation:请参阅从 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'] .该变量将在您的 PHP 代码中作为$_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.您可以随意操作它,然后再次向浏览器echo显响应,它将在data变量中可用。 references:参考:

jQuery AJAX jQuery AJAX

As javascript runs on user's browser you have to do an http request to a php page.由于 javascript 在用户浏览器上运行,您必须对 php 页面执行 http 请求。 POST or GET can be used to send parameters. POST 或 GET 可用于发送参数。

To make a http call with javascript refer to this: HTTP GET request in JavaScript?要使用 javascript 拨打 http,请参考: HTTP GET request in JavaScript?

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'];

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

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