-2

网址:http://localhost/test-mobile/log.php?username=&password=pass

$.ajax({
       url:url,
       type:'POST',
       data:{message:message},
       dataType:'json',
       json:'members',
       success:successData,
       error:function(){
        alert("error")
       }
      });
      function successData(data){
    var response=data.message;
    alert(response);
}

json响应是{"members":{"httpCode":"400","message":"Username missing"}}

PHP代码如下:

<?php
    require_once("class/clsdatabase.php"); //Connect to SQL 

$username = $_GET['username'];
$password = $_GET['password'];

    //Check Username
    if($username == '') {
        $user = 'Username missing';
        $success = true;
        $status = array("httpCode"=>"400", "message"=>$user);
        //return $status;
    }

    //Check Password
    if($password == '') {
        $pass = 'Password missing';
        $success = true;
    }


    //Create SELECT query
    $qry = "select * from user_register where emp_code='$username' AND emp_password='$password' AND active='1';";

    $result = mysql_query($qry);
    $te = mysql_num_rows($result);

    if($te == 0 && $username != '' && $password != '') {
        $both = 'Invalid username or password';
        $success = true;
    }


    //If there are input validations, redirect back to the registration form
    if($te != 0 && $username != '' && $password != '') {

        $row = mysql_fetch_assoc($result);
        $name = $row['emp_code'];
        $success = true;
        $status = array("httpCode"=>"400", "message"=>$name);
        //return $status;
    }

//echo $_GET['callback']. '(' . json_encode($status) . ');';    
echo '{"members":'.json_encode($status).'}';

?>

提醒 json 响应

4

2 回答 2

3

我会将页面分成两部分。一个名为 ajax.php 的文件和另一个名为 index.php 的文件。

你的 index.php 看起来像。

<html>
<head>
  <script type="text/javascript">

     postData={ajax:"testing",id:'123'};

     $.post('ajax.php', postData , function (data) {
       alert(data);
     });

  </script>
</head>
<body>

</body>
</html>

你的 ajax.php 文件看起来像

<?php

// its important that this file only outputs json or javascript 
// content and nothing else.

if(isset($_REQUEST['ajax'])){

  $ajaxRequest =  $_REQUEST['ajax'];

  if($ajaxRequest == 'testing'){

  // do some php stuff here -- if you look at the above example we sent an id variable
  $sql = "SELECT FROM table WHERE id = {$_REQUEST['id']}";

  $results = query($sql);

  echo json_encode($results);
  exit; // exit the script here so that only the ajax stuff is output

  }

}
于 2012-06-07T11:00:17.387 回答
0

如果设置了 dataType:'json' 参数(在他的查询中),jQuery .ajax 函数会自动解码 JSON 对象。所以传递给success()函数的'data'变量已经是一个javascript对象了。

要访问“消息”值,您将使用“data.members.message”,因为“成员”对象包含“消息”值。

于 2012-10-31T18:41:21.527 回答