一千萬個為什麽

搜索

使用jquery在zend框架中發布數據

如果你看看我有以下問題,我有一個表格(webbooks.phtml)我在其中使用jQuery函數

http://pastebin.com/7Pbd43fC -webbooks.phtml ( is actually a menu and in fact a view where you type the product that you are searching for)

http://pastebin.com/q8RJWdb7 -webbookscontroller ( this is a controller, which uses an API to get the data out of an SQL data base based on the string/number...etc given by the webbooks.phtml)

http://pastebin.com/vuy9GUvP -index.phtml (this is the view space where the result should be viewed.)

這是我得到的數組:

{"book_title":"Bioethics in the 21st Century",
"id":"1424",
"isbn":"978-953-307-270-8","
unix_name":"bioethics-in-the-21st-century",
"visible_online":"1"} 

我可以看到這個數組

die((json_encode)$result);

我想讓這個數組進入我的視圖(index.phtml)? 我是PHP的新手,我正在嘗試做一些可能不好的做法,可能是不可能的。我基本上只是在一起黑客攻擊測試我的知識,看看PHP能做些什麽。這可能嗎?

最佳答案

這是一個使用ajax/json調用Zend Controller的基本用法示例,並獲得對相同phtml的響應, 所以你可以在你的代碼中使用它。

在.phtml文件中我有javascript調用(在IndexController中)動作ajaxAction():

<script language = "Javascript">
var param1 = 'first';  //or get value from some DOM element
var param2 = 'second'; //or get value from some DOM element

jQuery.ajax({
      url: '/default/index/ajax',
      type: 'POST',
      data: {param1: param1, param2:param2 },
      dataType: "json",
      success: function(result){
            var return1 = result.return1;
            var return2 = result.return2;
           //return1 and return2 is value from PHP file.
           //fill out DOM element or do the windows.location()
      }
});
</script>

在IndexController中,ajaxAction()應該得到請求:

public function ajaxAction(){
    $this->view->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender(true);

    $param1 = $this->_request->getParam('param1');
    $param2 = $this->_request->getParam('param2');

   //DO THE OTHER STUFF AND LOGIC HERE

    $results = array(
        'return1' => 'value1',
        'return2' => 'value2'
    );

    $this->_response->setBody(json_encode($results));
}

無論如何,我建議聽@jakenoble並查看(學習)Zend中的Context Switching。

轉載註明原文: 使用jquery在zend框架中發布數據