[英]codeigniter get data via ajax and json from db
I have following problem: 我有以下问题:
View: 视图:
<script>
function show(id) {
$.ajax({
url: '<?php echo site_url('index.php/controller/show_id'); ?>',
dataType: 'json',
data:({id: id}),
type: "POST",
success: function (data) {
alert( data.user_id);
}
});
}
</script>
Controller: 控制器:
function show_id(){
$id= $this->input->post('id');
$id_list = $this->id_model->show_id($id);
$data['id'] = $id_list;
if($data['id']){
echo json_encode( $data['id'] );
} else {
echo json_encode( array('error' => true) );
}
}
If I load the page, I got "undefined" as an alert. 如果加载页面,则会收到“未定义”的警报。 If I change the JS to "alert(data);"
如果我将JS更改为“ alert(data);” I receive all content of the sql table.
我收到了sql表的所有内容。
How do I have to change the JS to get only "user.id" column? 如何更改JS以仅获取“ user.id”列?
please check type of data like that alert(typeof data);
请检查类似
alert(typeof data);
的数据类型(数据类型alert(typeof data);
if it
s get string then you need to convert your response in object and you can convert your response in object like that -- if it
是字符串,则需要将响应转换为对象,然后可以将响应转换为对象-
var result = JSON.parse(data);
and you are getting a single row or multiple rows ????? 并且您得到单行或多行????? if you are getting a single row then after convert in object you have to access
data.user_id
like that (after convert into object) -- 如果只有一行,那么在转换对象之后,您必须访问
data.user_id
这样的对象(转换为对象之后)-
var userId = result[0]['user_id];
please try this.. 请尝试这个。
You are getting undefined because the index user_id is not found in data. 由于在数据中找不到索引user_id,您将变得不确定。 you have too loop through the array first and then you can get value of data.user_id see below.
您也需要先遍历数组,然后才能获取data.user_id的值,请参见下文。
success: function (data) {
var data = JSON.parse(data);
console.log(data);
for (var x in data){
console.log(data[x].user_id);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.