【发布时间】:2014-01-07 08:34:22
【问题描述】:
我正在制作一个单页网站,它通过 CodeIgniter 中的 Ajax 与服务器交互。一般编码有以下几种:
controller (user.php):
public function get_user_content() {
$id = $this->input->post('id');
$hits = $this->user_model->user_data($id);
$s = '';
foreach ($hits as $hit) {
$s .= $hit->name;
$s .= $hit->age;
}
echo $s;
}
model(user_model.php):
function user_data($id) {
//do sql operation
return $query->result();
}
查看:
...
...
<a href="#" id="23" class="user-data">Click here for user details</a>
...
...
javascript:
('.user-data').click(get_user_data);
....
....
function get_user_data(response) {
return $.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/user/get_user_content",
data: { id: this.id },
success: function(response) {
$("#somediv").append(response);
$(".someclass").click(another_function);
},
error: function(error) {
alert("Error");
}
});
}
因此,查看上面的 javascript,所有将一些数据发送到服务器的操作都有单独的函数,并且特定的 html 内容通过 Ajax 更新。
我有以下问题(我只是对这些东西不熟悉):
1. Is there any better way of doing ajax in javascript than my implementation.
2. I'm not using the concept of views in CodeIgniter. I just `echo` results through my controller functions that gets embedded in javascript. This is because I want dynamic update in my app. It is a single page and there is no concept of new-page/new-tab. Is there any better way?
我不知道有任何开源项目可以使它更容易/更优化。
【问题讨论】:
-
第一个问题的答案是,ajax 请求很好,这是 jquery 中的标准方式
-
您尝试过下面建议的答案吗?它给你任何错误吗?
-
检查我提到的方式,如果您发现任何疑问,您可以通过 mhetreramesh@gmail.com 与我联系。--> 谢谢
-
已更新答案并附有详细说明。请检查
标签: javascript php jquery ajax codeigniter