1

我正在使用一本书来学习 javascript,并且我在最后一章中使用 jquery 教授 ajax。书中的例子不起作用。我什至从我发现作者上传并检查过的网站上下载了该文件。它只会在我尝试提交表单时弹出警报。这是代码:

    <!DOCTYPE html>
<html>
<head>
    <title>Ajax Form Submission</title>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>
        $(document).ready(function(){
            function checkFields(){
                return ($("#name").attr("value") && $("#email").attr("value"));
            }
            $("#form1").submit(function(){
                if(checkFields()){
                    $.post(
                        'test.php', $("#form1").serialize(),
                        function(data){
                            $("#div1").html(data);
                        }
                    );
                }
                else alert("Please fill in name and email fields!");
                return false;
            });
        });
    </script>
</head>
<body>
    <form id="form1">
        Name<input type="text" name="name" id="name"><br />
        Email<input type="text" name="email" id="email"><br />
        <input type="submit" name="submit" id="submit" value="Submit Form"> 
    </form>
    <div id="div1"></div>
</body>
</html>

这是它正在调用的 PHP:

<?php
echo "Name: ". $_Request['name'] . "<br />Email:" . $_Request['email'];
?>
4

1 回答 1

0

使用 jQuery 的val函数获取文本字段值:

function checkFields(){
   return ($("#name").val() && $("#email").val());
}

value编辑文本时浏览器不会更新属性。如果您使用.prop('value').

于 2013-03-26T02:19:40.683 回答