繁体   English   中英

如何从 php json_encode 正确解析 Json

[英]How to correctly parse Json from php json_encode

我想在我的前端应用程序中解析由 PHP json_encode 创建的 json 数据,我不能这样做:

var data= '<?php echo $jsonarr; ?>';

因为它是一个 Cordova 应用程序。 这是我的 php 代码:

 <?php
 $arr_login= array("lname"=>"$rowlname","email"=>"$rowemail","fname"=>"$rowfname","mobile"=>"$rowmobile");
  echo json_encode($arr_login);
 ?>

我的 ajax 代码:

   $.ajax({
   type:"POST",
   url: url,
   data:data,
   success: function(data){
   var res = $.trim(data);
   if (res == "Password is inccorrect" || res== "Email is inccorrect") {
    $("#errmsg").html(data);
   }
     else{
     var response= JSON.parse(data);
     alert(response);
     //window.open("dashboard.html?sess=logined&","_self");

     }
 }

     });

Now if I alert data it gives me the valid JSON format as sent by PHP, but I need to convert it to javascript object so I can use it in DOM but JSON.parse gives this error in the console:

 VM236:14 Uncaught SyntaxError: Unexpected token / in JSON at position 147
var response = JSON.parse(JSON.stringify(data));

为什么要提醒所有 json 变量,它绝对是 object? 我已经模拟了您的过程,正如@Anik Anwar 提到的JSON.stringify是解决方案

    <?php

        $rowlname = "row";
        $rowemail = "email";
        $rowfname = "rowfname";
        $rowmobile = "rowmobile";

        $arr_login= array("lname"=>"$rowlname","email"=>"$rowemail","fname"=>"$rowfname","mobile"=>"$rowmobile");
        $jsonarr = json_encode($arr_login);

    ?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>


    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>

    <script>
        var data = '<?php echo $jsonarr ?>';
    </script>

    <script>
        $.ajax({
            type: "POST",
            url: '/',
            data: data,
            dataType: 'json',
            contentType: 'application/json',
            success: function (data) {
                var res = $.trim(data);
                var response = JSON.parse(JSON.stringify(data));
                window.alert(response.lname);
            }

        });
    </script>

</body>

</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM