当我点击listproduct
(这是发票号)时,我会打开一个可折叠表,列出与发票号匹配的产品。
我的查看文件:
<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"]);
答案 0 :(得分:0)
jQuery的parseJSON()
函数将解析JSON字符串。
var resultObj = $.parseJSON( result );
alert(resultObj.records[1].invoiceno);
答案 1 :(得分: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>
答案 2 :(得分:-1)
alert(result['records'][1]["invoiceno"]);
这很有效!我只是得知它:)