显示来自 post jquery 的 json 数据


Display json data from post jquery

你好,我使用ajax的登录脚本,我想回调并显示我的数据 emailusernam将其存放在本地存储中。我可以在 JSON 中获取数据,但我想在控制台中显示这些数据.log

这是我的代码

send_ajax.js

   $(document).ready(function(e) {
$("#contactSubmitButton").click(function(){
        var email    = $("#contactEmailField").val();
        var password = $("#contactNameField").val();
    $.ajax({
    type: "POST",
    url: "http://hubafrica.co/webservices/get_user.php",
    data: "email="+email+"&password="+password,
    dataType: "json",
    cache: false,
    beforeSend: function(){ $("#contactSubmitButton").val('Chargement...');},
    success: function(data) {
        alert(data);
        if(data)
        {
             iterateJson(data);
             var url="http://hubafrica.co/webservices/get_user.php";
                    $.get(url,function(data){
                    // loop through the members here
                    $.each(json.data,function(i,dat){
                        console.log(dat.email);
                        window.localStorage.setItem("id", dat.id);

                    });
                  });

        //window.location.href = "user_dashboard.html";
        }else{
            $("#formSuccessMessageWrap").fadeIn('slow');
            $("#contactSubmitButton").val('se connecter');

        }

    },
        error: function (xhr, ajaxOptions, thrownError) {

      }
      });
    });
});

脚本.php

<?php 
header("Content-Type:application/json");
header('Access-Control-Allow-Origin: *');
include("../config/config.php");
$account=array();
if (isset($_POST["email"])){
                $email = htmlspecialchars($_POST["email"]);
                $pass =  htmlspecialchars($_POST["password"]);
                    $sql = mysql_query('SELECT * FROM `b2b_user` where email="'.$email.'" and password="'.$pass.'"');
                    $num = mysql_num_rows($sql);
                    if($num > 0){

                        $row = mysql_fetch_assoc($sql);
                        $account['id']  = $row['id'];
                        $account['email'] = $row['email'];
                        echo '{"members":'.json_encode($account).'}';
                    }
            }
?>

用于从后端发送响应,您需要在 JSON 中格式化数据。一旦你得到响应,你需要解析JSON((和你可以菜单板。

在此处更改:使用data.members访问数据:

在你的PHP结构中,像这样:不要附加字符串。

 $account1= array('members'=>$account);
 echo json_encode($account1);

脚本:

$.each(data.members,function(i,dat){
                        console.log(dat.email);
                        window.localStorage.setItem("id", dat.id);

                    });
您可以使用

 alert(JSON.stringify(data));

 Console.log(JSON.stringify(data));

以下代码行将对象/数组转换为 JSON 文本,并将该 JSON 文本存储在字符串中。

 JSON.stringify('/array variable here/')

希望对您有所帮助。