weixin_33696822 2019-02-08 14:50 采纳率: 0%
浏览 32

Ajax数据[0]未定义

I use ajax to get the number of rows (COUNT(*)) from a sql query in php.

The JSON return in Firefox-Network tab is:

[{"number":2}],

(the 2 is without quotes).

But in "ajax success" , when i try to get the value (2) from data[0]["number"] or data.length,it returns "undefined".

It works only if i parse JSON as object.

   $.ajax({
        url: 'queries.php?q=count',
        type: 'post',
        //data: data,
        datatype: 'json',
        success: function(data) { 

        //var dataobject = jQuery.parseJSON(data);
        //console.log(dataobject);
        //var var2 = dataobject[0].number; ---->THIS WORKS!
        //alert(JSON.parse(data).length); ---->THIS WORKS!

        //console.log(data.length); ---->Undefined 

        console.log(typeof data); ---->string
        console.log(data[0]["number"]);---->Undefined,i want this to work!!! 

      }
});

Thw SQL i use in php is :

      switch ($_GET["q"]) {

      case "count":
      $sql = "SELECT count(*) as number from 
            (SELECT Employees.emp_username, .............
                    where Employees.emp_username = ? and Year(emp)=2016  and    Month(emp)= MONTH(getdate()) ) as rows1 ";

      $stmt = sqlsrv_prepare( $conn, $sql , array(&$_SESSION["username"] ));
      break;

      default: header("Location: index.php"); }


      if( !$stmt ) { die( print_r( sqlsrv_errors(), true)); }
      sqlsrv_execute($stmt);
      $rows = array();

      if(sqlsrv_execute($stmt)){
      while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){

      $rows[] = $row;  }

     } else{
             die( print_r( sqlsrv_errors(), true));
   } 

     print json_encode($rows);
  • 写回答

2条回答 默认 最新

  • derek5. 2019-02-08 15:00
    关注

    Your variable type is string. You must parse it first.

    $.ajax({
            url: 'queries.php?q=count',
            type: 'post',
            //data: data,
            datatype: 'json',
            success: function(data) { 
    
            //var dataobject = jQuery.parseJSON(data);
            //console.log(dataobject);
            //var var2 = dataobject[0].number; ---->THIS WORKS!
            //alert(JSON.parse(data).length); ---->THIS WORKS!
    
            //console.log(data.length); ---->Undefined 
    
            console.log(typeof data); ---->string
    data = JSON.parse(data);
            console.log(data[0]["number"]);---->Undefined,i want this to work!!! 
    
          }
    });
    
    评论

报告相同问题?