2016-11-10 83 views
-1

当我点击listproduct(这是发票号)时,我将打开一个可折叠的表格,列出匹配发票号的产品。Ajax Json数据 - 如何访问返回的Json数据

我查看文件:

<script> 
$(document).ready(function(){ 
    $(".listproduct").click(function(){ 
     var value = $(this).text(); 
     alert(value); 
     $.post('<?=site_url("purchase_controller/getproductlist"); ?>', {data:value},function (result) { 
      alert(result[1][1]["invoiceno"]); 

      for(i=1;i<result["count"];i++){ //loop trough elements 
       $('#products tr:last').after('<tr><td>' + result[i]['invoiceno'] + '</td><td>' + result[i]['productname'] + '</td><td>' + result[i]['price'] + '</td></tr>'); 
      } 
     }); 

     $(".collapse").collapse('toggle'); 
    }); 
}); 
</script> 

<table id="products"> 
    <tbody> 
     <tr> 
      <td >Invoice No</td> 
      <td>productname</td> 
      <td> quantity</td> 
      <td> price</td> 
      <td> amount</td> 
     </tr> 
    </tbody> 
</table> 

我的控制器的文件:

public function getproductlist(){ 
    // check if is an ajax request 
    // if($this->input->is_ajax_request()){ 
    // echo "entered"; 

    // checks if the variable data exists on the posted data 
    if($this->input->post('data')){ 
     //query in your model you should verify if the data passed is legit before querying 
     $query = $this->purchasemodel->getproductlists($this->input->post('data')); 
     $data['records'] = $query['records']; 
     $data['count'] = $query['count']; 
     $this->output->set_content_type('application/json'); 
     $this->output->set_output(json_encode($data)); 

     return $data; 
    } 
    // } 
} 

我调试的时候输出 - 响应为Ajax:

{ "records": [ 
    {"id":"39","invoiceno":"55","price":"30000","quantity":"2", "amount":"60000","productname":"Tab"}, 
    {"id":"41","invoiceno":"55", "price":"200","quantity":"4","amount":"800","prod uctname":"zdsfS"} 
    ], 
    "count":2 
} 

但是,这是我得到的错误:

TypeError: result[1] is undefined 

alert(result[1][1]["invoiceno"]); 
+1

这是因为它是'undefined'。 '警报(result.records [0] .invoiceno);'。 – PHPglue

回答

-1
alert(result['records'][1]["invoiceno"]); 

这是工作!我只是要它:)

0

你需要解析你的json,然后你可以使用对象访问发票号码看我的代码片段。查看更多详细信息JSON here

<!DOCTYPE html> 
 
<html> 
 
<body> 
 

 
<h2>JSON Object Creation in JavaScript</h2> 
 

 
<p id="demo"></p> 
 

 
<script> 
 
var text = '{"records": [{"id":"39","invoiceno":"55","price":"30000","quantity":"2","amount":"60000","productname":"Tab"},{"id":"41","invoiceno":"55","price":"200","quantity":"4","amount":"800","prod uctname":"zdsfS"}],"count":2}'; 
 

 
var obj = JSON.parse(text); 
 
document.getElementById("demo").innerHTML = 
 
obj.records[1]['invoiceno'] + "<br>"; 
 

 
</script> 
 

 
</body> 
 
</html>