【问题标题】:Failed at AJAX POST request to the same page (with example)对同一页面的 AJAX POST 请求失败(示例)
【发布时间】:2012-01-18 18:28:42
【问题描述】:

代码

####### The name of this file is 'test_ajaxfn.php' #######
<?php
if($_POST['var']) {
    $result = $_POST['var'];
    echo $result.' is successfully passed to the same page using Ajax Post. :)';    
} else {
    echo 'There is no POST variable passed to the same page. :( ';  
}

echo '<br> Above indicates the ajax post function \'.\' ';
?>


<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>


<script>
$(document).ready(function() {
    $('#clickdiv').click(function() {
        var sth = "value to send to PHP";
        $.post(
        'test_ajaxfn.php',
        {"var":"1234567"},
        function(){
            alert('success');
            $('#clickdiv').text('the POST variable should be posted.');
        }
        );

    });
});
</script>

</head>

<body>
<div id="clickdiv" style="width: 50px; height: 50px; background:#CC3300; cursor:pointer;">
</div>
</body>
</html>

说明

我想将 POST 变量传递到同一页面并使用 AJAX 加载它。但是,我没有这样做。我无法使用 POST 方法将“var”传递给 $_POST['var']。因此我无法显示以下内容: 回声$结果。使用 Ajax Post 成功传递到同一页面。 :)';

我做错了什么?

参考

我实际上是在尝试解决这个问题: Calculate Google distance of Input address and all the address from MySQL Server using jQuery ajax.get 现在我简化了我的问题,但它仍然不起作用。请帮忙:(

【问题讨论】:

    标签: php jquery ajax


    【解决方案1】:

    如果您将其发布到同一页面,服务器会创建一个新进程来处理请求。您没有看到任何输出的原因是因为服务器正在查看文件的帖子,启动实例并执行 php 脚本,但这与您的 php 线程不同。将您的脚本更改为此以查看您的成功文本。

    <script>
    $(document).ready(function() {
        $('#clickdiv').click(function() {
            var sth = "value to send to PHP";
            $.post(
            'test_ajaxfn.php',
            {"var":"1234567"},
            function(result){
                alert(result);
                $('#clickdiv').text('the POST variable should be posted.');
            }
            );
    
        });
    });
    </script>
    

    【讨论】:

    • 嗨!感谢您的答复!我已尝试根据您的建议更改代码。但是,我在弹出框中获得了成功文本,以及弹出框中的整个 HTML 代码。 "1234567 使用 Ajax Post 成功传递到同一页面。:)
      上面表示 ajax post 函数'。
    • 而且,页面仍然没有变为成功文本。它仍然是“没有 Post 变量传递给同一页面 :(”。
    • 做得很好,现在继续在最后一个回声上方添加 if(if($_POST['var'])){exit();}。
    • @ChrisYeung “而且,页面仍然没有变为成功文本”,如果您在加载后使用 javascript 更改它,您只会看到您的网站版本发生变化。
    • 感谢您的帮助。我想在同一页面上测试 ajax.post 功能的原因是因为我遇到了更复杂的问题HERE。我不能用 Javascript 来做,因为我不想将敏感数据从 MySQL 数据库传递给 JS。因此,我想在服务器端执行此操作,然后在同一页面上进行更新。但是,这似乎是不可能的..
    猜你喜欢
    • 2012-01-21
    • 1970-01-01
    • 2014-06-29
    • 2015-01-28
    • 2011-07-04
    • 2011-11-08
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多