簡體   English   中英

將 javascript 變量傳遞給 PHP function

[英]Passing javascript variable to PHP function

我有這個 javascript 代碼

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

    }
</Script>

我需要將groupFirstLetter傳遞給 PHP function,這將計算該組中有多少用戶並將值返回給 javascript function。

有什么想法嗎?

謝謝,

您可以使用 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
        }
});

該變量將在您的 PHP 代碼中作為$_POST['groupFirstLetter'] 您可以隨意操作它,然后再次向瀏覽器echo顯響應,它將在data變量中可用。 參考:

jQuery AJAX

由於 javascript 在用戶瀏覽器上運行,您必須對 php 頁面執行 http 請求。 POST 或 GET 可用於發送參數。

要使用 javascript 撥打 http,請參考: HTTP GET request in JavaScript?

使用 jQuery (jquery.com)。

使用 ajax 動態加載發送變量的 php 文件,如下所示:

$.post("file.php", {variable_name: value}, function(returned_data){
    console.log(returned_data); //or do whatever you like with the variable
});

並且您的 php 文件將訪問該變量:

$_POST['variable_name'];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM