weixin_33728708 2016-01-25 09:53 采纳率: 0%
浏览 36

在PHP中用$ .ajax回显$ _POST

I'm trying to echo $_POST with $.ajax in PHP with no success. In Xdebug I see the $_POST get the right value and executing the echo $_POST line, but I keep getting the else output clause. Also in chrome I see the headers that are sent valid. All the code is in the same page index.php.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery.post demo</title>
    <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>

<button type="button" id="but">Click Me!</button>

<script>
    $('#but').click(function() {
        $.ajax({
            type: "POST",
            url: "index.php",
            data: {name: "John"},
            success: function() {
                alert('success');
            }
        });
    });
</script>
</body>
</html>

<?php

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    echo $_POST['name'];
} else {
    echo "Nothing to Show";
}
?>
  • 写回答

2条回答 默认 最新

  • weixin_33711641 2016-01-25 09:59
    关注

    At the moment the whole page is being returned in response to your AJAX request; HTML and all. You're also not retrieving the value returned from the request in your JS code, to do that you just need to accept a parameter on your success handler. Try this:

    In it's own file, say foo.php:

    <?php
        if ($_SERVER['REQUEST_METHOD'] == "POST") {
            echo $_POST['name'];
        } else {
            echo "Nothing to Show";
        }
    ?>
    

    Then in your HTML:

    <script>
        $('#but').click(function() {
            $.ajax({
                type: "POST",
                dataType: 'text', // to ensure jQuery doesn't try to deserialise the repsonse
                url: "foo.php",
                data: { name: "John" },
                success: function(response) {
                    console.log(response.trim()); // = 'John'
                }
            });
        });
    </script>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)