0

目前,我无法从我的 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']
));
4

1 回答 1

1

您正在为提交事件创建处理程序,但您似乎忘记返回 false 以停止基本提交过程。

具有空操作的表单将在同一页面(您的初始 PHP 页面)中发布数据,因此发送了 AJAX 回调,但之后,您将再次以基本方式发布。

return false在函数末尾添加一个(就在您的 AJAX 调用之后),然后您的表单将不会被提交,AJAX 将被发送,您将看到响应。

如果您使用的是 Firefox,请安装 Firebug 并查看 Network 选项卡以查看 Ajax 调用发送的请求并检查您的 JSON 响应。

祝你好运。

于 2013-02-08T02:44:24.837 回答