繁体   English   中英

看不到php变量的值

[英]Can not see the value of php variable

我有一个php文件,单击按钮后从哪里运行save_match()

function save_match() {
    ...
    $.post('url2', {elements: elements});
    ...
}

并运行另一个php文件,其中包含以下内容:

<?php
    $tok = 1024;
    if($_POST['elements'])
    {
            echo '<script>foo("'.$tok.'") </script>';  
    ...
?>
<html>
  <body>
    <script type="text/javascript">
    function foo(p1) {
        //alert(p1);
         document.write("|"+p1+"|");
        }     
    </script>
  </body>
</html>

我这样做的原因是,由于echo我什么都看不到。 好吧,现在我看到了更多。

我也在新标签页中打开了url2 但是,在按url1中的按钮并转到第二个url的选项卡后,没有任何更改。 我刷新了,但是什么都没有改变!

我能做什么? 我需要这个来进行调试。

您可以执行以下操作来查看令牌的值。

  1. 从您的php文件中删除所有html标记,因为它们不是必需的。
  2. 删除函数foo。 和脚本
  3. 将您的代码更改为关注。

     <?php if (isset($_POST['elements'] && $_POST['elements'])) echo $tok; ..... 
  4. 将您的JavaScript更新为:

      function save_match() { ... $.post('url2', {elements: elements}, function($token) { console.log($token); // will print your token in javascript console }); ... } 
<html>
  <body>
    <?php
      $tok = 1024;
      if(isset($_POST['elements']))
      {
          echo $tok;
      }
    ?>
  </body>
</html>

这应该工作。 确保设置了doctype以及所有其他文档,并且还设置了POST中的变量元素。 也许if函数总是会失败,因为没有设置任何元素。

对于您尝试做的事情,您实际上不需要JavaScript。

等待异步动作的函数示例:

function save_match(){
  var somethingToReturn, pushTo = [];
  $.post('url2.php', {saveMatch:1, simple:'column_value_here', anotherProp:'Example'}, function(phpComesBackHere){
    $.each(phpComesBackHere, function(i, o){
      pushTo.push(o.object_property);
    });
    somethingToReturn = pushTo;
  });
  while(1){
    if(somethingToReturn){
      return somethingToReturn;
    }
  }
}

在url2.php上,它像:

<?php
include 'secure_database_connection.php'; $db = db(); // function db is returning `new mysqli('host', 'username', 'password', 'database');`
if(isset($_POST['saveMatch'])){
  if(+$_POST['saveMatch'] === 1){
    if(isset($_POST['simple'], $_POST['anotherProp'])){
      if($qry = $db->query("SELECT * FROM table_name WHERE column={$_POST['simple']}")){
        if($qry->num_rows > 0){
          while($r = $qry->fetch_object()){
            $returnArray[] = array('object_property' => $r->your_property_here, 'anotherProp' => $r->and_another_property);               
          }
          echo json_encode($returnArray);
        }
        $qry->free();
      }
    }
    else{
      // simple and/or anotherProp hack
    }
  }
  else{
    // saveMatch hack
  }
}
elseif(isset($_POST['somethingElse'])){
  // this could be separate $.post on same page
}
$db->close();
?>

暂无
暂无

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

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