2012-07-11 15 views
1

我想做的事情基本上是每3秒檢索一次div和sub div內容。我正在使用ajax將數據發送到控制器。但我越來越帶時間間隔的Ajax調用zend框架

$.ajax is not a function 
http://localhost/index/editor 
Line 25 

這是我使用的代碼。

<script type="text/javascript"> 
    window.setInterval(getAjax, 3000); 

    function getAjax() { 
     $.ajax({ 
      type: "POST", 
      url: 'localhost/index', 
      data: "some-data"  
     }); 
    } 

</script> 

1)我做錯了什麼

2)如何接收的Zend控制器

+0

您是否包含了jQuery(或Zepto)? – Florent 2012-07-11 15:12:05

+0

Jquery包含在我的默認佈局中,並禁用它。這是否有效? – user1515244 2012-07-11 15:15:58

回答

0

$.ajax數據由jQuery的定義。在調用此函數之前,您必須包含它。

1

一旦jQuery包含在您的頁面中,您將能夠使用$ .ajax()函數。之後,在您的控制器中,您可以訪問$ _POST變量中的數據。爲了更方便,我通常使用JSON對象將數據發送到控制器:

<script type="text/javascript"> 
     window.setInterval(getAjax, 3000); 

     var data = {}; 
     data['field1'] = 'value1'; 
     data['field2'] = 'value2'; 
     function getAjax() { 
      $.ajax({ 
       type: "POST", 
       url: 'localhost/index', 
       data: data  
      }); 
     } 

    </script> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"> 

而在你的控制器,你可以使用_getParam找到一個值:

public function ajaxAction() { 
    //Disable the view (if this is an AJAX call) 
    if($this->getRequest()->isXmlHttpRequest()) { 
     $this->_helper->layout()->disableLayout(); 
     $this->_helper->viewRenderer->setNoRender(); 
    } 

    //Get posted data 
    $field1 = $this->_getParam('field1'); 
    $field2 = $this->_getParam('field2'); 

    if($field1=='value1') { 
     $jsonResp['isValid'] = 1; 
     $jsonResp['gotValue'] = $field2; 
    } 
    header('Content-type: application/json'); 
    echo Zend_Json::encode($json); 
} 

編輯: 哦,我忘了,你可能會想要檢查你的控制器從你的jQuery代碼發送的響應。您可以通過以下方式實現該功能:

$.ajax({ 
//... 
success: function(jsonResp) { 
    if(jsonResp['isValid']) alert(jsonResp['gotValue']); 
} 
});