3

我创建了一个脚本来读取哈希(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。

我有一个 foreach 循环遍历函数中的帖子(发布 ID)。我需要将 HASH 传递到函数中,并每次将其与发布 ID 进行比较。唯一的问题是,$_GET['hash'] 不会出现在函数内部。

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

5 回答 5

3

像这样使用ajax,发送哈希值

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

现在你会得到

<?php echo $_POST['hash']; ?>
于 2013-04-01T10:45:36.473 回答
3
<script>
    var hash = location.hash;
    $.post("community.php", {
        hash: hash
    }, function(responde){ alert(responde); });
</script>

检查您的 PHP 响应:)

于 2013-04-01T10:45:51.143 回答
2

$.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

虽然这是一个矫枉过正,除非你想在同一个脚本中一遍又一遍地调用该函数。如果它在没有功能的情况下工作,你应该这样做。

于 2013-04-01T11:02:57.400 回答
1
  <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']:'';

希望它会给你一些解决方案。

于 2013-04-01T10:50:24.480 回答
0

但哈希没有在 post 变量中回显

这是因为如果您想在页面加载时发送它,那么您必须在doc ready处理程序中使用它:

<script>
  $(function(){
     var hash = location.hash;
     $.post("community.php", { hash: hash });
     alert(hash);
  });
</script>
于 2013-04-01T10:59:05.453 回答