Zend Framework - Ajax



AJAX 是一種現代的 Web 程式設計技術。它提供了一種在網頁中非同步傳送和接收資料的方法,而無需重新整理頁面。Zend 框架提供了一種透過 **json** 模型以及 **zend-view** 和 **zend-json** 元件來處理 AJAX 的方法。在本節中,我們將學習 Zend AJAX 程式設計。

安裝 json 元件

Zend json 元件可以使用如下所示的 **Composer** 命令安裝:

composer require zendframework/zend-json 

概念

Zend 框架提供了兩種簡單的方法來編寫支援 AJAX 的 Web 應用程式。它們分別是:

  • **Request** 物件中的 **isXmlHttpRequest()** 方法 – 如果發出了 AJAX 請求,則請求物件的 isXmlHttpRequest() 方法將返回 true,否則返回 false。此方法用於在伺服器端正確處理 AJAX 請求。

if ($request->isXmlHttpRequest()) { 
   // Ajax request 
} else { 
   // Normal request 
}
  • **Zend/View/Model/JsonModel** – **JsonModel** 是 **ViewModel** 的替代方案,專門用於 AJAX 和 REST API 場景。JsonModel 與 **JsonStrategy**(在模組的檢視管理器塊中配置)一起將模型資料編碼為 **Json** 並將其作為響應返回,而不是檢視(phtml)。

AJAX – 工作示例

讓我們在教程模組中新增一個新的 ajax 頁面 **ajax**,並非同步獲取書籍資訊。為此,我們應該遵循以下步驟。

步驟 1:在模組配置中新增 JsonStrategy

更新教程模組配置檔案 – myapp/module/Tutorial/config/module.config.php 中的檢視管理器塊。然後,**JsonStrategy** 將與 **JsonModel** 協同工作,對 json 資料進行編碼併發送。

'view_manager' => [ 
   'template_map' => array
      ('layout/layout' => __DIR__ . '/../view/layout/newlayout.phtml'), 
   'template_path_stack' => [ 
      'tutorial' => __DIR__ . '/../view', 
   ], 
   'strategies' => array('ViewJsonStrategy',), 
],

步驟 2:在 TutorialController.php 中新增 ajaxAction 方法

使用以下程式碼在 TutorialController.php 中新增 ajaxAction 方法:

public function ajaxAction() { 
   $data = $this->bookTable->fetchAll(); 
   $request = $this->getRequest(); 
   $query = $request->getQuery();  
   if ($request->isXmlHttpRequest() || $query->get('showJson') == 1) { 
      $jsonData = array(); 
      $idx = 0; 
      foreach($data as $sampledata) { 
         $temp = array( 
            'author' => $sampledata->author, 
            'title' => $sampledata->title, 
            'imagepath' => $sampledata->imagepath 
         );  
         $jsonData[$idx++] = $temp; 
      } 
      $view = new JsonModel($jsonData); 
      $view->setTerminal(true); 
   } else { 
      $view = new ViewModel(); 
   }  
   return $view; 
} 

在這裡,ajaxAction 將檢查傳入的請求是否為 AJAX 請求。如果傳入的請求是 AJAX 請求,則將建立 **JsonModel**。否則,將建立普通的 **ViewModel**。

在這兩種情況下,書籍資訊都將從資料庫中獲取並填充到模型中。如果模型是 JsonModel,則將呼叫 **JsonStrategy**,它將資料編碼為 json 並作為響應返回。

**$query->get('showJson') == 1** 用於除錯目的。只需在 URL 中新增 **showJson=1**,頁面將顯示 json 資料。

步驟 3:新增 ajax.phtml

現在,為 ajaxAction 方法新增檢視指令碼 **ajax.phtml**。此頁面將包含一個標籤為“載入書籍資訊”的連結。

單擊該連結將發出 AJAX 請求,該請求將以 Json 資料的形式獲取書籍資訊,並以格式化的表格形式顯示書籍資訊。AJAX 處理使用 **JQuery** 完成。

完整的程式碼清單如下:

<a id = "loadbook" href = "#">Load book information</a> 
</br> </br> 

<table class = "table"> 
   <tbody id = "book"> 
   </tbody> 
</table>  

<script language = "javascript"> 
$(document).ready(function(){  
   $("#loadbook").on("click", function(event){ 
      $.ajax({ 
         url:        '/tutorial/ajax', 
         type:       'POST',  
         dataType:   'json', 
         async:      true, 
         
         success: function(data, status) { 
            var e = $('<tr><th>Author</th><th>Title</th><th>Picture</th></tr>'); 
            $('#book').html(''); 
            $('#book').append(e); 
            
            for(i = 0; i < data.length; i++) { 
               book = data[i]; 
               var e = $('<tr><td id = "author"></td><td id = "title"></td>
               <td id="imagepath"><img src = ""/></td></tr>'); 
               $('#author', e).html(book['author']); 
               $('#title', e).html(book['title']); 
               $('#imagepath img', e).attr('src', book['imagepath']); 
               $('#book').append(e); 
            } 
         }, 
         error : function(xhr, textStatus, errorThrown) { 
            alert('Ajax request failed.'); 
         } 
      }); 
   }); 
}); 
</script>

步驟 4:執行應用程式

最後,執行應用程式 - **https://:8080/tutorial/ajax** 並單擊“載入書籍資訊”連結。

結果將如下所示:

**Ajax 頁面** -

Ajax Page

包含書籍資訊的 Ajax 頁面

Book Information

包含除錯資訊的 Ajax 頁面

Debugging Information
廣告