简体   繁体   English

如何在 javascript 中获取 json_encode php

[英]how to get json_encode php in javascript

I want to send this $data我想发送这个 $data

if($query == true)
{
   
    $data = array(
        'status'=> true,
        'result' => 1
       
    );
}

echo json_encode($data);

then I want to retrieve the data然后我想检索数据

success: function(data) {
    console.log(data.status);
}

In the console is undefined , but if I console.log(data) , the data is called.在控制台中是undefined ,但如果我console.log(data) ,则调用数据。

a) Either use JSON.parse() a) 要么使用JSON.parse()

success: function(data) {
    data = JSON.parse(data);
    console.log(data.status);
    console.log(data.result);
}

b) Or in your ajax request add this only: b) 或者在您的 ajax 请求中仅添加:

dataType: 'json'

You need to parse json data to use in javascript.您需要解析 json 数据以在 javascript 中使用。

success: function(data) {

  if ( typeof data !=="undefined" ) {
     var result = JSON.parse(data);
     console.log(result);
  }

}

your data might still be a string, and you need to parse it to object first.您的数据可能仍然是一个字符串,您需要先将其解析为对象。 You can use JSON.parse .您可以使用JSON.parse

let json = '{"test":"val"}';
console.log(JSON.parse(json).test); // will output val

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

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