-2

URL :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

ページを 2 つに分割します。1 つのファイルは ajax.php と呼ばれ、もう 1 つのファイルは 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オブジェクトになります。

'message'値にアクセスするには、'members'オブジェクトに'message'値が含まれているため、"data.members.message"を使用します。

于 2012-10-31T18:41:21.527 に答える