2017-07-07 22 views

回答

1

下面是使用ZF3 Ajax請求的一個簡單的例子。你可以試試這個。在這個例子中,我們將使用ZF3的默認Application模塊。

讓我們假設我們將通過來自以下url的ajax調用來檢索數據。

http://yoursite.com/title 

允許創建在IndexControllertitle路線的操作方法。

public function titleAction() 
{ 
    // Initialize view 
    $view = new ViewModel(); 

    // Checks if this is a Javascript request 
    $xmlHttpRequst = $this->getRequest()->isXmlHttpRequest(); 

    if (! $xmlHttpRequst) { 
     die('Bad request'); 
    } 

    /** 
    * Here we may pull data from database but for tests 
    * here we make an array of titles for the view 
    */ 
    $titles = []; 
    for ($i = 0; $i < 10; $i++) { 
     $titles[] = "Lorem ipsum dolor {$i}"; 
    } 

    // Set data to be used in the view 
    $view->setVariable('titles', $titles); 

    /** 
    * Tell the renderer not to show the layout 
    * by setting setTerminal to true 
    */ 
    $view->setTerminal(true); 

    return $view;   
} 

我們創建了一個方法,我們需要爲它創建一個視圖模板。

視圖/應用/索引/ title.phtml

<?php 
foreach ($titles as $title) { 
    echo '<h2>' . $title . '</h2>'; 
} 

現在,我們將創建一個從那裏我們會用Ajax調用在IndexController另一種操作方法。

http://yoursite.com/text 

所以讓我們作出這樣的操作方法太...

public function textAction() 
{ 
    return new ViewModel(); 
} 

和視圖模板會像這樣

視圖/應用/索引/ text.phtml

<h1>Handling ajax request</h1> 

<button onclick="showTitle()">Show Title</button> 

<div id="box"></div> 

<?php 
    // Set url 
    $url = $this->serverUrl('/title'); // http://yoursite.com/title 

    // This is for the "url" catch 
    echo "<script>" . PHP_EOL; 
    echo "\tvar url = '{$url}';" . PHP_EOL; 
    echo "</script>" . PHP_EOL; 
?> 

<script> 
    function showTitle() { 
     $.get(url, function(data){ 
      $('#box').html(data); 
     }) 
     .done(function(){ 
      console.log('Done!'); 
     }) 
     .fail(function(){ 
      console.log('Failed!'); 
     });  
    } 
</script> 

這個腳本需要jQuery Javascript庫來製作ajax呼叫。因此,請確保該腳本已添加到您的view/layout/layout.phtml中。

我們需要的最後一件事是爲/title/text設置路線。讓我們這兩個路由添加到模塊/應用/配置/ module.config.php

'title' => [ 
    'type' => Literal::class, 
    'options' => [ 
     'route' => '/title', 
     'defaults' => [ 
      'controller' => Controller\IndexController::class, 
      'action' => 'title', 
     ], 
    ], 
], 
'text' => [ 
    'type' => Literal::class, 
    'options' => [ 
     'route' => '/text', 
     'defaults' => [ 
      'controller' => Controller\IndexController::class, 
      'action' => 'text', 
     ], 
    ], 
], 

性的路段讓我們知道,如果它使你快樂!

+0

它的運作良好,但我想展示的例子ajax我無法發送或接收數據之間的Ajax和行動 –

相關問題