簡體   English   中英

Ajax驅動的內容使用CodeIgniter

[英]Ajax driven content using CodeIgniter

我正在制作一個網頁,這是一個單頁網站,通過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,對於將一些數據發送到服務器的所有操作都有單獨的函數,並且通過Ajax更新特定的html內容。

我有以下問題(我只是對這個東西不熟悉):

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? 

我不知道任何可能使其更容易/更優化的開源項目。

為了使代碼更簡化,可讀性和良好的編碼標准答案將是肯定的 ,以改善您的JavaScript代碼和您從Ajax調用獲得響應的方式。

  1. 改進Javascript :如果沒有創建和包含一個,你可能在頭部分中包含一個常見的js。 這個常見的jar只包含整個應用程序中的常用功能。 使用名稱創建一個函數可能就像common.js中的 sendAjaxRequest()一樣。 這個函數將有一些參數,如divId (刷新div id), url (post 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調用中重新定義:在ajax調用的情況下,您可以在Controller-> function中加載視圖,不需要為此更改或配置。 使用這種方式始終是保持代碼中標准性和可讀性的良好實踐。

注意:在這種情況下,您可能會擔心在第一次Ajax調用的加載時使用第二個操作,因為這種標准方法是在該特定Ajax調用視圖的加載視圖上編寫第二個操作(在該特定視圖中寫入第二個單擊代碼)只要)
喜歡

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


簡而言之,最終用戶划分和征服規則(將html頁面划分為塊並創建大頁面)以創建良好的應用程序。 它真的很棒,因為我在整個編碼中使用這種方式。

第一個答案:

ajax請求似乎很好,你也可以添加dataType選項以期望特定類型的響應,因為你正在使用post你可以使用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" );
})

您也可以使用完成回調而不是成功

第二個答案:

調節器

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

1-還有其他方法可以進行ajax調用,不管是不是更好是基於你的需求, 這篇文章清楚了解這一點

2-你的方式是好的,你仍然可以使用一些功能的增強功能,成為一個完整的Web服務,與處理錯誤相同 - 以防萬一 - 並將輸出數據作為json返回,允許您從JavaScript函數控制它更好的處理和代表性。

3-從我所知道你每次都獲得單個用戶的數據,在這種情況下使用$query->row()將比使用$query->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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM