目前,我无法访问我的jquery ajax返回的数据。实际上,我甚至不知道我是否正在发送任何数据?我只需要将数据从一个带有JSON的表单发送到php,并以数组的形式获得响应。
谢谢你的帮助。
HTML/JS/jQuery
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
    <title>Hello World</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <script src="https://github.com/douglascrockford/JSON-js/blob/master/json2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("form").submit(function () { 
                var uname = document.getElementById("username").value;
                var pword = document.getElementById("password").value;
                var postData = {
                    username: uname,
                    password: pword
                };
                alert(uname);
                $.ajax({
                url: "test.php",
                type: "GET",
                data: postData,
                dataType: 'json',
                contentType: 'json',
                cache: false,
                success: function (data) {
                        alert(data);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form action="">
        <input type='text' id="username" name="username" placeholder="Username" />
        <br />
        <input type='password' id="password" name="password" placeholder="password" />
        <br />
        <input type="submit" id="submit" value="Login" />
    </form>
</body>
PHP
echo json_encode(array(
    'username' => $_GET['username'],
    'password' => $_GET['password']
));发布于 2013-02-08 10:44:25
您正在为submit事件创建一个处理程序,但是为了停止基本的提交过程,您似乎忘记了返回false。
具有空操作的表单将在同一页面(最初的PHP页面)中发布数据,因此将发送AJAX回调,但在此之后,您将再次以基本方式发布数据。
在函数的末尾(就在AJAX调用之后)添加一个return false,然后您的表单将不会被提交,AJAX将被发送,您将看到响应。
如果您使用的是Firefox,请安装Firebug并查看Network选项卡,以查看Ajax调用发送的请求并检查JSON响应。
祝好运。
https://stackoverflow.com/questions/14764664
复制相似问题