在Zend框架中使用Ajax Search需要帮助

时间:2011-04-05 09:32:18

标签: javascript ajax zend-framework dojo

我是网络编程的新手,所以请耐心等待。我想要做的是让用户从Dojo自动完成组合框中选择一个值,并将结果显示在同一页面上。我曾试图关注Phil Brown的优秀博客文章http://blog.philipbrown.id.au/2011/03/awesome-pagination-with-zf-paginator-ajaxcontext-and-the-html5-history-api/,但说实话,尤其是与JavaScript方面相关的问题。我也尝试实现http://www.w3schools.com/php/php_ajax_database.asp,但无济于事,因为它在第一次尝试时将我的整个页面和结果呈现在页面本身,并且再次更改组合框中的值,没有任何内容传递给我的JS函数(我得到XMLHttpRequest()未定义。 到目前为止我所做的是关注Phil的博客

  1. 为我的搜索操作创建了一个AjaxContext。

  2. 创建了一个search.ajax.phtml文件并从我的search.phtml文件中调用它

  3. 在我的表单中为我的Dojo Combobox添加了一个onChange事件

  4. 根据W3Schools示例创建了一个JS脚本来处理on change事件。

  5. 任何人都可以帮助我,我看到了我能想到的所有地方,但仍然没有快乐。

    我的搜索操作代码在下面,我一直保持检查提交按钮的操作,因为它阻止我不得不刷新页面。

    public function searchAction()
     {
       // Generate the form
       $form = new PetManager_Form_SearchBreeds;
       $this->view->form = $form;
    
       $input=$_GET["input"];
    
       if($input=$_GET["input"]){
        $b=$input;
            $q = Doctrine_Query::create()
            ->from('PetManager_Model_Breeds b')
            ->leftJoin('b.PetManager_Model_Pettype p')
            ->addWhere('b.breed LIKE ?',"$b%");
    
            // Execute query and attach results to the view
            $results=$q->fetchArray();
            $this->view->results=$results;
       }else if($form->isValid($this->getRequest()->getParams())){
                $input = $form->getValues();
                 $q = Doctrine_Query::create()
                ->from('PetManager_Model_Breeds b')
                ->leftJoin('b.PetManager_Model_Pettype p');
    
                // attach criteria to base query
                if(!empty($input['breed'])){
                $b=$input['breed'];
    
                 $q->addWhere('b.breed LIKE ?',"$b%");
                }
    
            // Execute query and attach results to the view
            $results=$q->fetchArray();
            $this->view->results=$results;
        } 
    
    }
    

    我的JS代码如下

    function getBreedDetails(str)
     {
       if (window.XMLHttpRequest)
       {// code for IE7+, Firefox, Chrome, Opera, Safari
         xmlhttp=new XMLHttpRequest();
           // testing only window.alert("XMLHTTP Request"+str);
       }
      else
       {// code for IE6, IE5
         xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          // testing only window.alert("MICROSOFT.XMLHTTP Request"+str);
       }
      xmlhttp.onreadystatechange=function()
      {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
          {
    
            document.getElementById("records").innerHTML=xmlhttp.responseText;
          }
       }
     xmlhttp.open("GET","/breeds/breed/search?input="+str,true);
     xmlhttp.send();
    
    }
    

    我的表格代码如下

    public function init()
    {
    
        // Initialise form
    
        $this->setAction('/breeds/breed/search')
              -> setMethod('get');
    
    
         // Create a autocomplete input for breed name that fires an onChange event     
        $breedName = new Zend_Dojo_Form_Element_ComboBox('breed',array('onChange'=>"Javascript:getBreedDetails(breed.value)"));
        $breedName->setLabel('Breed Name');
                $breedName->setOptions(array(
                'autocomplete' => false,
                'storeId'   => 'breedStore',
                'storeType' => 'dojo.data.ItemFileReadStore',
                'storeParams' => array('url' => "/breeds/breed/autocomplete"),
                'dijitParams' => array('searchAttr' => 'breed')
          ))
                ->setRequired(true)
                ->addValidator('NotEmpty', true)
                ->addFilter('HTMLEntities')            
                ->addFilter('StringToLower')        
                ->addFilter('StringTrim');
    
        // create a submit button
        $search = new Zend_Form_Element_Submit('submit');
        $search->setLabel('Search')
               ->setOptions(array('class'=>'submit'));
    
    
         // attach elements to the form
        $this->addElement($breedName)
             ->addElement($search);     
    
    
      }
    

    我的search.ajax.phtml文件如下所示,只是使用echo命令从search.phtml文件中调用它

    <?php if(count($this->results)):?>
     <div id="records">
       <table>
        <tr>
        <td class="key">
        Breed
        </td>
        <td class="key">
         Tpye
        </td>
        </tr>
        <?php foreach ($this->results as $r):?>
        <tr>
         <td><?php echo $this->escape($r['breed']);?></td>
         <td><?php echo $this->escape($r['PetManager_Model_Pettype']['type']);?></td>
         <td><a href="<?php echo $this->url(array('id' => $r['breedID']), 'breeds-display'); ?>"> <img src='/images/view.png'/></a></td> 
         <td><a href="<?php echo $this->url(array('id' => $r['breedID']), 'breeds-update'); ?>"><img src='/images/updateico.png'/></a></td>   
         </tr>
         <?php endforeach;?>
         </table>
    
        </div>  
         <?php else:?>
         No Breeds Found
         <?php endif;?>
    

    任何帮助都非常感激,因为这会让我的脑袋融化,并且我的项目暂时停止,因为我需要其他模块的这个功能。

    由于

    格雷厄姆

2 个答案:

答案 0 :(得分:0)

嗯,您需要先将问题本地化。要查看它是在服务器端(PHP)还是JS。熟悉Firebug。找出发送到服务器的实际请求以及服务器是否发回预期结果。 是时候学习调试和帮助你的工具了。

答案 1 :(得分:0)

由于您使用的是Dojo,因此您也可以使用其内置的Ajax功能......

以下是有点奇怪的:

$input=$_GET["input"];

if($input=$_GET["input"]){

首先,您应该使用正确的Zend Framework方法,即。使用$this->_getParam('input');而不是访问$ _GET / $ _ POST / $ _ REQUEST对应项。

所以用以下代替:

$input = $this->_getParam('input');

if (!is_null($input)) {

然后针对你的实际问题(我猜不管怎么说):要从你的AJAX调用中返回数据,你很可能应该确保Zend Framework不会使用视图模板呈现数据(当然,除非你做一个单独的.phtml以正确的格式返回数据)。因此,您应该使用$this->_helper->viewRenderer->setNoRender();关闭视图渲染器,如果您使用的是布局管理器,请同时禁用它$this->_helper->layout()->disableLayout();。并在脚本结束时以客户端脚本(很可能是JSON)所期望的格式返回数据。

总而言之,您的Ajax搜索操作代码应该如下:

$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout()->disableLayout();

// fetch params & process, store results in $results

$this->getResponse()->setBody(Zend_Json::encode($results));

哦,顺便说一下,如果可能的话,你应该考虑对实际的ajax搜索使用单独的动作,而不是在显示/处理你的搜索表单的动作中混合它...