Were using jquery autocomplete in zend and setup our action like this
public function ajaxautocompleteAction()
{
$postData = $this->_request->getParams();
$term = $postData['term'];
$categoryObj = new Categories();
$result = $categoryObj->searchCategory($term);
$this->view->result = $result;
}
The javascript in the view file is this
$(function() {
var url = "http://www.domain.com/account/ajaxautocomplete?format=json";
开发者_如何学C $( "#autotest" ).autocomplete({
minLength: 2,
source: function(request, response){
var iterm = request.term;
var url = "http://www.domain.com/account/ajaxautocomplete?format=json";
$.post( url, {term: iterm},
function( data ) {
response(data); });
}
});
});
In chrome console i get this error
XMLHttpRequest cannot load http://www.domain.com/account/ajaxautocomplete?format=json. Origin http://domain.com is not allowed by Access-Control-Allow-Origin.
Any ideas why were not getting results from the ajax request?
This is how I've used jQueryUI's autocomplete and ZF before...
Create your action
public function ajaxautocompleteAction() { $term = $this->getRequest()->getParam('term'); $categoryObj = new Categories(); $result = $categoryObj->searchCategory($term); $this->view->result = $result; }
Add an AjaxContext to your action, disabling automatic JSON serialisation. I'm skipping the auto serialisation as it's not common for your models to represent the usual "label" / "value" pairs jQueryUI's automcomplete looks for
public function init() { $this->_helper->ajaxContext->addActionContext('ajaxautocomplete', 'json') ->setAutoJsonSerialization(false) ->initContext('json'); }
Create your JSON view (
views/scripts/account/ajaxautocomplete.json.phtml
)<?php $data = array(); foreach ($this->results as $category) { // format each result for jQueryUI autocomplete $data[] = array( 'label' => $category->getName(), 'value' => $category->getName() ); } echo Zend_Json::encode($data);
Add the URL for your autocomplete action as a JavaScript variable to the view that needs to use it (assuming you use the HeadScript helper in your layout)
$this->headScript()->prependScript(sprintf('var searchUrl = "%s";', $this->url(array( 'action' => 'ajaxautocomplete', 'controller' => 'account' ), null, true)));
Setup your JavaScript like this
$("#autotest").autocomplete({ source: searchUrl, minLength: 2 });
looks like domain.com does not allow cross-domain calls.
Try chrome.exe --disable-web-security
精彩评论