【问题标题】:Ajax driven content using CodeIgniter使用 CodeIgniter 的 Ajax 驱动内容
【发布时间】: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


【解决方案1】:

第一个答案:

ajax 请求看起来不错,您也可以添加 dataType 选项来期待特定类型的响应, 当您使用帖子时,您可以使用jquery.post 作为替代

例子

$.post( "<?php echo base_url();?>index.php/user/get_user_content", function(data) {
  alert( "success" );
}, 'html') // here specify the datatype
.fail(function() {
  alert( "error" );
})

你也可以使用 done 回调而不是 success

第二个答案:

控制器

public function get_user_content() { 
    $id = $this->input->post('id');
    $hits = $this->user_model->user_data($id);
    $user_array = array();
    foreach ($hits as $hit) {
       $temp_array = array();
       $temp_array = array('name' => $hit->name);
       $temp_array = array('age' => $hit->age);  
       $user_array = array($temp_array);

    }
    $this->load->view('user', $user_array);
}

模态

保持不变

查看 (user.php)

例如说user.php

<?php
echo "<div class='somediv'>";
if (sizeof($user_array)) {
  for ($row = 0; $row < sizeof($user_array); $row++ ) {
     echo "User Details: Name - " . $user_array[$row]['name'] . ", Age - " . $user_array[$row]['age']; 
     echo "<br/>";
  }      
} else { 
  <a href="#" id="23" class="user-data">Click here for user details</a>
} 
echo "</div>";
?>

Javascript

$('.user-data').on('click' function () {  // better to use event delegation as content is loaded dynamically
   get_user_data(); 
});

function get_user_data() {
    $.post( "<?php echo base_url();?>index.php/user/get_user_content", function(data) {
      alert( "success" );
      $("#somediv").append(data);
      $(".someclass").click(another_function);
    }, 'html') // here specify the datatype
    .fail(function() {
      alert( "error" );
    });
}

参考

stackoverflow.com/questions/18471627/codeigniter-load-a-view-using-post-and-ajax

【讨论】:

    【解决方案2】:

    为了使代码更简化、更易读并且具有出色的编码标准答案将是,这对于改进您的 javascript 代码和从 Ajax 调用获得响应的方式而言都是如此。

    1. 改进 Javascript : 如果没有创建并包含一个,您的标题部分中可能包含一个常见的 js。这个通用 jar 仅包含整个应用程序中的通用功能。在 common.js 中创建一个名称可能类似于 sendAjaxRequest() 的函数。此函数将有一些参数,如 divId(刷新 div id)、url(发布 url)、options(选项数组)和函数将看起来像这样:

      function sendAjaxRequest(strDivId, strRequestUrl, options) {
           options = options || {};
           var defaultOptions = {url: strRequestUrl, type: 'POST', beforeSend: function(request,options){showLoadingImage(strDivId);}, success: function(html){$('#'+strDivId).html(html); removeLoadingImage(strDivId); }};
           options = $.extend({},defaultOptions,options);
           $.ajax(options);
      }
      

      从应用程序需要的地方调用此函数。 喜欢

      ('.user-data').click( function() { sendAjaxRequest('somediv', url,{data: { id: this.id }}) });

      好处:当您希望在 ajax 调用上保留谷歌分析或想要跟踪您的 ajax 调用时,此方法在将来非常有用。有共同的功能总是好的。

    2. 来自 ajax 调用的响应: 您也可以在 Controller->function 中加载视图以防 ajax 调用,无需为此进行任何更改或配置。使用这种方式始终是保持代码的标准性和可读性的好习惯。

    注意:在这种情况下,您可能会担心在加载第一个 Ajax 调用时使用第二个操作,因为这种标准方式是在加载该特定 Ajax 调用视图的视图时编写第二个操作(在仅限该特定视图)
    喜欢

    ('.someclass').click( function() { sendAjaxRequest('someOtherDiv', otherUrl,{data: { id: this.id }}) });


    简而言之,在最终用户分而治之规则(将 html 页面分成块并创建大页面)来创建良好的应用程序。这是一种非常棒的方式,因为我在整个编码中都使用这种方式。

    【讨论】:

      【解决方案3】:

      1- ajax调用还有其他方法,好不好看你自己的需要,This post说明了这一点

      2- 你的方法很好,你仍然可以对你的函数进行一些增强,使其成为一个完整的 web 服务,就像处理错误一样——以防万一——并将输出数据作为 json 返回,从而允许你从 JavaScript 控制它功能以获得更好的处理和表示。

      3-据我了解,您每次都在为单个用户获取数据,在这种情况下,使用 $query-&gt;row() 会比使用 $query-&gt;result() 更容易提取数据,但如果您获得多条记录你可以用你的 JavaScript 函数循环它。

      这是您的示例的另一种方法,几乎​​没有改进,可能会有所帮助:

      controller (user.php):

      public function get_user_content($id) {
          $output -> hit = $this -> user_model -> user_data($id);
          if (!$output -> hit) {
              $output -> msg = "NORECORDS";
          } else {
              $output -> msg = "SUCCESS";
          }
          echo json_encode($output);
      }
      

      model(user_model.php):

      function user_data($id) {
          //do sql operation
          return $query -> row();
      }
      

      JavaScript:

           function get_user_data(response) {
          $.get("<?php echo base_url();?>index.php/user/get_user_content/" + this.id, function(data) {
              if (data.msg != 'SUCCESS') {
                  alert(data.msg);
                  return;
              }
              var hit = data.hit;
              $("#somediv").append("Name: " + hit.name + "Age: " + hit.age);
              $(".someclass").click(another_function);
          }, "json");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-06-19
        • 2012-07-28
        • 1970-01-01
        • 2013-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多