簡體   English   中英

將變量從jQuery傳遞給PHP

[英]Pass variable from jQuery to PHP

我創建了一個腳本來讀取哈希值(www.website.com/#hash)並將哈希值傳遞給php。 alert(hash)彈出哈希值,但哈希值不會在post變量中回顯。 知道為什么嗎?

jQuery頁面

<script>
    var hash = location.hash;
    $.post("community.php", {
        hash: hash
    });
    alert(hash);
</script>

Community.php頁面

<?php echo $_POST['hash']; ?>



編輯 - 下面的$ _GET最初是$ _POST以上。

我有一個循環通過在函數中發布(發布ID)的foreach。 我需要將HASH傳遞給函數並每次將其與發布ID進行比較。 唯一的問題是,$ _GET ['hash']不會出現在函數內部。

function something() {
   echo $_GET['hash'];
}

像這樣使用ajax,以hash形式發送值

  function send_hash(hash) {
    $.ajax({
      url   : "community.php", 
      type  : "POST",
      cache : false,
      data  : {
        hash : hash
      }
    });
  }

現在你會得到的

<?php echo $_POST['hash']; ?>
<script>
    var hash = location.hash;
    $.post("community.php", {
        hash: hash
    }, function(responde){ alert(responde); });
</script>

檢查你的PHP響應:)

$ .post是一個ajax事件。 您正在通過ajax發布數據,因此該頁面不會轉到communitypage.php。 對於你想要的行為你必須做普通的表格發布而不是ajax發布。 $ .post將使用此代碼檢索您在communitypage.php上回顯的任何內容。

//Note the 3rd argument is a callback.
var hash = location.hash;
$.post('communitypage.php',{hash:hash},function(data){
    alert(data);
});

在該頁面上處理哈希並在找到哈希值時發出警告。 你會在data找到回聲

您可以修改communitypage.php以返回html,如下所示

<?php
if($isset($_POST["hash"]) && strlen(trim($_POST["hash"])) > 0){
    echo "Hash found :: " . $_POST["hash"]; 
}else
    echo "No hash found";
?>

注意這將返回html,您可以根據需要修改響應以返回xml,json。

有關詳細信息,請參閱jQuery post()文檔

對於更新的問題

它在外面工作,因為當ajax調用是在函數內部調用時調用它,因為函數沒有被調用。 如果你想這樣做(我不知道為什么),你可以這樣做。

function myfunction(){
    //your code goes here
}

myfunction(); //call the function so that the code in the function is called upon

雖然這是一種矯枉過正,除非你想在同一個腳本中反復調用該函數。 如果它在沒有功能的情況下工作,你應該這樣做。

  <script>
  var hash = location.hash;
   //Try this.
   window.location.href = 'community.php?val='+hash;
  </script>

要么

   <script>
   $.post("community.php","val="+hash);
   </script>

在community.php中

     $res=isset($_REQUEST['val'])?$_REQUEST['val']:'';

希望它會給你一些解決方案。

但是在post變量中沒有回顯哈希

這是因為如果你想在頁面加載時發送它,那么你必須在doc ready處理程序中使用它:

<script>
  $(function(){
     var hash = location.hash;
     $.post("community.php", { hash: hash });
     alert(hash);
  });
</script>

暫無
暫無

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

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