在哪里使用json_encode()并发出这个AJAX请求

时间:2014-06-05 13:20:25

标签: javascript php jquery ajax json

我必须使用getthedb.php文件对用户进行身份验证,该文件应该以JSON格式接收数据(使用json_encode()函数完成)。这应该以JSON格式再次发送响应。我想使用我所做的这个结构,还有一个我不知道如何编写和使用的回调函数。此用户名和密码应为json_decode()文件中的getthedb.php,用户名和密码可与数据库中的条目匹配。成功后,它应该重定向到主页。                                                            

    function checkPassword()
       {    
    var username = $("#username").val();
    var password =$("#password").val();

    $.ajax({
        url: "/getthedb.php",
        type:"POST",
        contentType: "application/json",
        data: JSON.stringify(userdetails),
        success: function mycallback() 
            {

                alert("hi");    
            }
    });

        }

          </script>
          <body>

      <form method="post">
    <label for="username">Username: </label>
    <input type="text" name="username" id="username" placeholder="Username" 
            required />
    <label for ="password">Password</label>
    <input type="password" name="password" id="password" placeholder="Password"
             required />
    <button value="Submit" onClick="checkPassword()">Submit</button>
      </form>


             </body>
             </html>

我用Google搜索了很多,每次都找到不同的方法。 请不要接受xmlhttp对象方法。为我提供一些研究材料,以便更好地理解这些ajax请求,在哪里写这些,如何发起这些请求(比如在xmlhttp中我们使用open()setrequestheader()send()函数)。我刚刚开始使用这些东西,并且非常渴望学习编写Web服务。

1 个答案:

答案 0 :(得分:0)

您不需要JSON.stringify您发送的数据,只需传入JSON对象,这应该在$ _POST变量下显示为服务器上的数组。

此外,您没有userdetails变量。我建议将data属性设置为

data: {
    "username": username,
    "password": password
}

这些将通过$ _POST ['username']和$ _POST ['password']

来实现