在PHPAX中将PHP JSON编码数组转换为JavaScript数组?

时间:2014-04-29 08:14:30

标签: javascript jquery ajax json cordova

我无法将AJAX响应转换为JavaScript数组。我收到的只是[object Object]在我的提醒框中。

var url = 'list_devices.php';
var modurl = url;
alert(modurl);
ajax.open("GET", modurl, true);
ajax.onreadystatechange = function () {
    if (ajax.readyState == 4) {
        if (ajax.status == 200) {
            //var json = JSON.stringify(ajax.responseText);
            var me = JSON.parse(ajax.response);
            //var me=jQuery.parseJSON(responseData);
            //alert(me);
            alert(json);
            //var uid=new Array();
            //uid=me.split(",");
            //$.mobile.navigate("#page1");
            //$('#devices').empty();
            //var temp=document.createElement('li');
            //for (var i=0; i<uid.length; i++) {
            //$('#devices').append('<li ><p>'+uid[i]+'</p></li>'); -->
            //}
            //$('#devices').append(temp);
        }
    }
}
ajax.send(null);
}

PHP:

(我正在尝试获取会话中存储的user_id的所有IMEI。)

<?php
  header("content-type:text/javascript");
  session_start();
  $sql=new mysqli("hostname","user","pass","dbname");
  if(!$sql):
      echo "error connecting to database";
      die();
  else:
     $i=0;
     $temp=[];
     $q="SELECT imei FROM tbl_user_device where user_id='".$_SESSION['user_id']."'";
     $result=$sql->query($q);
     while($output=$result->fetch_array()):
        echo json_encode($output);      
     endwhile;
  endif;
?>

2 个答案:

答案 0 :(得分:1)

[object Object]是对象的字符串表示,当您在警报中看到解析成功时。

使用console.log(me);查看对象的内容


<edit/>

看起来你想要返回一个结果数组并迭代这个数组来打印数据。

目前您返回一个对象,您必须使用此对象填充数组(或者在需要时填充多个对象):

php返回一个数组:

<?php
  //the correct MIME-type for json is application/json
  header("content-type:application/json");
  session_start();

  //use your data here
  $sql=new mysqli("hostname","user","pass","dbname");

  if(!$sql):
      echo "error connecting to database";
      die();
  else:

     $temp=[];
     //I've modified the query to return multiple rows
     //but it will work also with a single row
     $q="SELECT  imei,user_id FROM tbl_user_device";

     $result=$sql->query($q);

     //you better use fetch_assoc here 
     while($output=$result->fetch_assoc()):
        //populate the array with results
        $temp[]=$output;

    endwhile;
 endif;
 //print the json
 die(json_encode($temp));
?>

迭代结果:

    var url = 'list_devices.php';
    var modurl = url;

    ajax.open("GET", modurl, true);
    ajax.onreadystatechange = function() {
      if (ajax.readyState == 4) {
        if(ajax.status == 200) {
          var me= JSON.parse(ajax.response);
          //iterate over the array-items
          for (var i=0; i<me.length; i++) {
            var li=$('<li/>');
              //iterate over the properties 
              //of the current array-item
              for(var k in me[i]){
                li.append($('<p/>')
                            .append($('<strong/>').text(k+':'))
                            .append($('<code/>').text(me[i][k])));
              }
              $('#devices').append(li);
          }
        }
      }
    }

    ajax.send(null);

答案 1 :(得分:0)

这是因为您的数据未被解析。请尝试以下代码。你有回调函数吗?

 $.ajax({
          type:"GET",
          url:"http://hostname/list_devices.php",
          crossDomain:true,
          dataType:'jsonp',
          success: function jsondata(data)
               {
                var jsondata=JSON.parse(JSON.stringify(data));
                var datap=jsondata["Status"];
                     alert(datap);
               }

        });

    or try JSON.parse(JSON.stringify(ajax.response));