【问题标题】:CakePHP can't get ajax GET workingCakePHP 无法让 ajax GET 工作
【发布时间】:2017-12-12 07:16:39
【问题描述】:

我似乎无法让 AJAX POST 或 GET 与我的 CAKEPHP 网站一起工作。我正在尝试创建自动完成功能,但似乎无法使用 ajax 提交或获取数据。我可以使用标签自动完成工作,但无法显示表格中的数据。如果我没有使用正确的 url 或其他问题,我不确定出了什么问题。 这是我的 search.ctp

<?php use Cake\Routing\Router; ?>

    <?php echo $this->Form->input('id', ['type' => 'text']); ?>

<script>
    $.ajax({
    type:       "POST",
    url:        "<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>",
    success:    function(response) {
        $("#id").autocomplete({ source: response });
    }
});
</script>

这是我在 InvoicesController 中的搜索功能。

    public function search()
{
    $this->loadComponent('RequestHandler');
    if ($this->request->is('ajax')) 
    {
        $name = $this->request->query['term'];
        $resultArr = $this->Invoices
    ->find()
    ->where(
        ['Invoices.id LIKE' => ($name . '%')],
        ['Invoices.id' => 'string']
    );

        $resultsArr = [];
        foreach ($resultArr as $result) 
        {
             $resultsArr[] = (strval($result['id']));
        }

        $this->set('resultsArr', $resultsArr);
        // This line is what handles converting your array into json
        // To get this to work you must load the request handler
        $this->set('_serialize', ['resultsArr']);


    }
}

这是我尝试输入 ID 时产生的错误。

这就是我想要生成的,我可以通过在 search.ctp 中使用数组来完成

这是我试图从中获取 ID 的表。

【问题讨论】:

  • 它甚至似乎一开始都没有找到您的 PHP 文件,因此查询或表不是问题。也许您的 AJAX 请求的 URL 格式不正确。将预期的 URL 写入控制台,看看是否正确。
  • 我猜你的 Cake 路由也有可能没有正确设置。
  • 您应该检查网络选项卡以确定正在发送和接收的内容,同时检查您的错误日志。顺便说一句,请求处理程序组件。应该在initialize() 方法中加载(默认情况下它通常已经在AppController 中)。

标签: javascript php jquery ajax cakephp


【解决方案1】:

有两种方法。

  1. $this-&gt;request-&gt;query('term');
  2. $_REQUEST['term'];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    相关资源
    最近更新 更多