【问题标题】:my php isset is not working in POST method我的 php isset 在 POST 方法中不起作用
【发布时间】:2020-09-23 02:36:28
【问题描述】:

这是我的 test.php 代码

<input type="button" value="click me" name="my_btn" onclick="mybtn();">

<?php
    echo("before is set");

    if(isset($_POST['hello'])=="dear"){
    echo("after is set true");
}
?>

<script src="vendor/jquery/jquery.min.js"></script>

<script>
function mybtn(){

        $.ajax({
            url:"http://localhost/mysites/php_two/test.php",
            method:"post",
            data:{hello:"dear"},
        });

    }
</script>

当按钮被点击时,页面只显示 仅按钮图标 +“设置之前”文本。

但在 Devtools 网络预览中(在 chrome 浏览器中),它显示 按钮图标 +" before is setafter 设置为 true"

请帮我解决这个问题。

【问题讨论】:

  • 网络预览显示响应包含的内容,这意味着isset 正在工作。示例代码缺少done函数,任何从AJAX调用返回的东西都必须在done函数中处理,这就是AJAX的思想,请求不会触发页面加载。
  • isset() 将返回一个 bool,然后您将它与一个 string 进行比较,这永远不会是真的。你想要if(isset($_POST['hello']) &amp;&amp; $_POST['hello'] == "dear")

标签: javascript php jquery ajax post


【解决方案1】:

我认为这需要至少 2 个 PHP 页面,第一个用于显示数据,第二个用于创建数据
show.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input type="button" value="click me" name="my_btn" onclick="mybtn();">
<div id="dis">before is set</div>
<script>
   function mybtn(){

        $.ajax({
            url: "data.php",
            type: "POST",
            data:{hello:"dear"},
            success: function(result){
                $("#dis").html(result);
            }
        });

    }
</script>

data.php

<?php
    if(isset($_POST['hello']) && $_POST['hello']=="dear"){
        echo("after is set true");
     }
?>

【讨论】:

    【解决方案2】:

    你不能混合if(isset($_POST['hello'])=="dear"),因为 isset() 接受一个变量并检查它是否已设置,而不是返回布尔值的 NULL,而是像这样单独使用它:

    if(isset($_POST['hello']) && $_POST['hello']=="dear")
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多