首页 文章

POST请求后为什么显示页面?

提问于
浏览
0

抱歉这个奇怪的 Headers . 我有以下代码测试jquery的post()函数:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>Untitled Document</title>
<script type="text/javascript" src="../../jquery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
     $(document).ready(function() {

        $("form#f").submit(function(){
            var result = "";
            $.ajax({
                async: false,
                type: "POST",
                url: "test.php",
                dataType: "script",
                success: function(data){
                    result = data;
                }
            });
            alert(result);
        });

     }

</script>
</head>

<body>

<form method="post" action="test.php" id="f">
    <input type="text" name="name" />
    <input type="submit"/>
</form>

</body>
</html>

...这是test.php实现:

<?php 
    header('Content-Type: text/plain');
    echo "hello " . $_POST['name'];
?>

为什么在submit()函数的警告对话框中显示的页面而不是数据?对不起我知道这是一个n00b问题 . 我不是很擅长Javascript .

3 回答

  • 2

    在提交处理程序的末尾执行 return false; . 否则,您无法阻止正常提交(post to test.php)

    $("form#f").submit(function(){
                var result = "";
                $.ajax({
                    async: false,
                    type: "POST",
                    url: "test.php",
                    dataType: "script",
                    success: function(data){
                        result = data;
                        alert(result);  // And move that here
                    }
                });
                return false;  // Here
    
            });
    
  • 0

    返回false的替代方法是使用jQuery的event.preventDefault()

    $("form#f").submit(function(e){
            e.preventDefault();
            // do stuff
        });
    
  • 1

    @Jairo我尝试了你的原始代码,它使用了CDN .

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    

相关问题