将javascript变量传递给PHP函数

alk*_*der 2 javascript php

我有这个javascript代码

<Script>
    function getGroupId(){
        var group=document.getElementById("selectedOptions").value;
        var groupFirstLetter=group.substring(2);

    }
</Script>
Run Code Online (Sandbox Code Playgroud)

我需要传递groupFirstLetter给PHP函数,该函数将计算该组中有多少用户并将值返回给javascript函数.

有什么想法吗?

谢谢,

Son*_*ngo 6

您可以使用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
        }
});
Run Code Online (Sandbox Code Playgroud)

该变量将在您的PHP代码中可用$_POST['groupFirstLetter'].您可以根据需要操作它,然后echo再次对浏览器进行响应,它将在data变量中可用.引用:

jQuery AJAX