使用已知密钥获取返回的json的值

时间:2017-09-04 07:08:05

标签: php jquery

我有这个PHP代码返回一些json

public function my_account(){
             header("Access-Control-Allow-Origin: *");
           header("Access-Control-Allow-Methods: PUT, GET, POST");
           header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
           $email_posted = $this->input->post('email');
           $email = preg_replace('/\s+/', '', $email_posted);

            $where = "email='$email'";

            $this->db->where($where);


            $query = $this->db->get('users');

            if ($query->num_rows() > 0)
            {
               foreach ($query->result() as $row)
               {
                  $json = array("id"=>$row->id, "email"=>$row->email,"names"=>$row->names,"country"=>$row->country,"password"=>$row->password,"telephone"=>$row->telephone);
                  echo json_encode($json);
               }
            }

         }

返回的json是这种格式

{"id":"15","email":"corn64@gmail.com","names":"Cern 64","country":"","password":"cern!768","telephone":"00000"}

获取jquery中的数据

$.each(data, function(i, obj) {
        alert(obj.email);
});

并且有这个小提琴https://jsfiddle.net/c5b4o6yh/2/

我收到错误

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

  

{ “ID”: “15”, “电子邮件”: “corn64@gmail.com”, “名称”:“欧洲核子研究中心   64" , “国家”: “”, “密码”: “CERN 768!”, “电话”: “00000”}

使用已知密钥获取值的正确方法是什么?。

4 个答案:

答案 0 :(得分:1)

这肯定是一个问题: -

1.您在$json

中覆盖了foreach()变量

2.您只在foreach()内发送单一回复。

更改以下代码(更改已注释): -

public function my_account(){
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: PUT, GET, POST");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
    $email_posted = $this->input->post('email');
    $email = preg_replace('/\s+/', '', $email_posted);

    $where = "email='$email'";

    $this->db->where($where);


    $query = $this->db->get('users');
    $json = array(); //define variable as an array variable
    if ($query->num_rows() > 0)
    {
       foreach ($query->result() as $row)
       {
          $json []= array("id"=>$row->id, "email"=>$row->email,"names"=>$row->names,"country"=>$row->country,"password"=>$row->password,"telephone"=>$row->telephone);//assign values to array

       }
    }
    echo json_encode($json); // send response after loop completion
 }

现在您的原始脚本代码将起作用。

答案 1 :(得分:1)

首先,将值保存在数组中。((使用array_push()函数可以将一个或多个元素插入到数组的末尾))

dlmwrite('/Users/amar/Desktop/geenrated/rate.txt', [newTime intHeartRate intRespRate]);

答案 2 :(得分:0)

在这种情况下,您的响应应该是数组,而不是简单的对象。因此,尝试重新编写代码以返回

[{"id":"15","email":"corn64@gmail.com","names":"Cern 64","country":"","password":"cern!768","telephone":"00000"}]

jsfiddle是正确的。

答案 3 :(得分:0)

使用JSON.parse(data)将JSON字符串从您的端点转换为JS对象,然后获取各个键值:

var obj = JSON.parse(data);
var id = obj.id;