使用AJAX从PHP返回JSON

时间:2014-12-02 23:58:16

标签: php jquery ajax json

如果这是一个重复的问题,请道歉,但我在这里找到的任何答案都没有给我带来帮助。我正在尝试为一个网站创建一个简单的登录功能,该网站使用对PHP的AJAX调用,它应返回JSON。我有以下PHP:

<?php
include("dbconnect.php");
 header('Content-type: application/json');
 $numrows=0;
 $password=$_POST['password'];
 $username=$_POST['username'];
 $query="select fname, lname, memcat from members where (password='$password' && username='$username')";
 $link = mysql_query($query);
 if (!$link) {
  echo 3;
  die();
 }
 $numrows=mysql_num_rows($link);
 if ($numrows>0){  // authentication is successfull
   $rows = array();
   while($r = mysql_fetch_assoc($link)) {
    $json[] = $r;
   }

   echo json_encode($json);  
  } else {
  echo 3;  // authentication was unsuccessfull
 }
?>

AJAX电话:

$( ".LogIn" ).live("click", function(){
    console.log("LogIn button clicked.")
    var username=$("#username").val();
    var password=$("#password").val();
    var dataString = 'username='+username+'&password='+password;

         $.ajax({
          type: "POST",
          url: "scripts/sendLogDetails.php",
          data: dataString,
          dataType: "JSON",
          success: function(data){
              if (data == '3') {
             alert("Invalid log in details - please try again.");
             }

              else {
             sessionStorage['username']=$('#username').val();
             sessionStorage['user'] = data.fname + " " + data.lname;
             sessionStorage['memcat'] = data.memcat;
             storage=sessionStorage.user;
             alert(data.fname);
             window.location="/awt-cw1/index.html";
             }
            }
           });
}

正如我所说的,每当我运行这些来自&#34; data&#34;未定义。知道我哪里出错了吗?

非常感谢。

0 个答案:

没有答案