CakePHP ajax调用:发生错误:未定义

CakePHP AJAX-Call: An error occured: undefined

本文关键字:错误 未定义 调用 CakePHP ajax      更新时间:2023-09-26

我试图得到一些示例ajax应用程序运行与cakephp。我开始读这篇博文:http://www.dereuromark.de/2014/01/09/ajax-and-cakephp/,我试图把它应用到我的建筑中。

现在我被困在这里:当我更改第一个选择框的选择时,我得到一个错误警告:undefined。

当我尝试在浏览器中直接调用AJAX-URL时,它实际上返回了正确的html内容,应该在第二个选择框中更新,但我看到有一个500服务器错误也被返回,表示它无法加载资源http://localhost/favicon.ico。这就是为什么ajax调用说"发生错误"的问题吗?我不知道为什么这个资源甚至被调用,为什么它在localhost/而不是应用程序文件夹中查找。有人能告诉我需要做什么才能让ajax-sample运行吗?这是ajax调用的js代码:

<script>
$(function() {
$('#countries').change(function() {
    var selectedValue = $(this).val();
    var targeturl = $(this).attr('rel') + '?id=' + selectedValue;
    $.ajax({
        type: 'get',
        url: targeturl,
        beforeSend: function(xhr) {
            alert(targeturl);
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        },
        success: function(response) {
            alert(response);
            if (response.content) {
                alert("content");
                $('#provinces').html(response.content);
            }
        },
        error: function(e) {
            alert("An error occurred: " + e.responseText.message);
            console.log(e);
        }
    });
});
});
</script>

这些是我的控制器函数:

public $components = array('Session','RequestHandler');
...
public function chained_dropdowns() {
    $countries = $this->TestRun->find('list');
    $countryProvinces = array();
    foreach ($countries as $key => $value) {
        $countryProvinces = $this->TestRun->TestStepRun->find('list',array('conditions'=>array('TestStepRun.test_run_id'=>$key)));
        break;
    }
    $this->set(compact('countries', 'countryProvinces'));
}
public function country_provinces_ajax() {
    //$this->request->onlyAllow('ajax');
    $id = $this->request->query('id');
    if (!$id) {
        throw new NotFoundException();
    }
    //$this->viewClass = 'Tools.Ajax';
    //$this->loadModel('Data.TestStepRun');
    $countryProvinces = $this->TestRun->TestStepRun->find('list',array('conditions'=>array('TestStepRun.test_run_id'=>$id)));
    $this->set(compact('countryProvinces'));
}
}

我在routes.php中添加:

Router::parseExtensions();
Router::setExtensions(array('json'));

(更新)我只是将错误输出行更改为:

alert("An error occurred: " + e.responseText);

现在,我得到错误消息:" An error occured: <option value="">... "这是来自json视图的数据,应该传递给success-函数。我只是不知道为什么会抛出错误

可能是,这是一个问题与您的jquery请求配置?

也许试着添加

dataType:"html",在你的美元里。ajax配置。

解决问题。通常CakePHP只输出你输入到。ctp -文件中的内容。

如果你没有在那里定义json,你将不会得到任何对象(不管控制台说什么)。