首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何处理来自jQuery AJAX的PHP响应?

如何处理来自jQuery AJAX的PHP响应?
EN

Stack Overflow用户
提问于 2013-02-08 10:15:04
回答 1查看 2.8K关注 0票数 0

目前,我无法访问我的jquery ajax返回的数据。实际上,我甚至不知道我是否正在发送任何数据?我只需要将数据从一个带有JSON的表单发送到php,并以数组的形式获得响应。

谢谢你的帮助。

HTML/JS/jQuery

代码语言:javascript
运行
复制
<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

代码语言:javascript
运行
复制
echo json_encode(array(
    'username' => $_GET['username'],
    'password' => $_GET['password']
));
EN

Stack Overflow用户

回答已采纳

发布于 2013-02-08 10:44:25

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

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

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

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

祝好运。

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14764664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档