猿问

如何在编解码器 4 中使用 ajax

我正在使用代码签名-4版本,并尝试在导航栏中自动搜索。我正在尝试使用ajax将后方法中的数据发送到控制器中。但它不起作用。而共签名器 4 没有描述 ajax 的细节。下面我的代码示例输入框是 -


<input class="form-control mr-sm-2" type="search" placeholder="<?= lang('nav.search'); ?>" aria-label="Search" name='s' id="seachBox">

阿贾克斯代码是 -


     $.ajax({  

       url:<?= base_url('search'); ?>,

       headers:{'X-Requested-With':'XMLHttpRequest'},

       data:{query:query},

       success:function(data){

             alert(data);

       }  

    });

而我的控制器是 -


<?php

class Search extends BaseController

{

    public function __construct()

    { 

        helper(['common_helper','aws_helper']);

    }


    public function index(){


        echo 'string';

    }

}

?>

路线是 -


<?php 


$routes->get('/search', 'Search::index');


?>


天涯尽头无女友
浏览 100回答 1
1回答

慕容森

下面是 ajax 的示例代码。(确保您已为搜索 URL 定义了路由/控制器方法)$.ajax({&nbsp;&nbsp;&nbsp; &nbsp; url:<?php echo base_url('search'); ?>,&nbsp; &nbsp; type: 'post',&nbsp; &nbsp; dataType:'json',&nbsp; &nbsp; data:{query:query},&nbsp; &nbsp; success:function(data){&nbsp; &nbsp; &nbsp; &nbsp; alert(data);&nbsp; &nbsp; }&nbsp;&nbsp;});CI4 代码获取请求数据if ($this->request->isAJAX()) {&nbsp; &nbsp; $query = service('request')->getPost('query');&nbsp; &nbsp; var_dump($this->request->getPost('query'));}此外,如果您没有成功重新加载页面,请确保更新每个请求。此外,您需要在方法中返回令牌。因此,在这种情况下,您的方法将如下所示 -csrf tokencsrfif ($this->request->isAJAX()) {&nbsp; &nbsp; &nbsp; &nbsp; $query = service('request')->getPost('query');&nbsp; &nbsp; &nbsp; &nbsp; //var_dump($this->request->getPost('query'));&nbsp; &nbsp; &nbsp; &nbsp; return json_encode(['success'=> 'success', 'csrf' => csrf_hash(), 'query ' => $query ]);&nbsp; &nbsp; }因此,在这种情况下,您的ajax代码将如下所示 -$.ajax({&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; url:<?php echo base_url('search'); ?>,&nbsp; &nbsp; &nbsp; &nbsp; type: 'post',&nbsp; &nbsp; &nbsp; &nbsp; dataType:'json',&nbsp; &nbsp; &nbsp; &nbsp; data:{query:query},&nbsp; &nbsp; &nbsp; &nbsp; success:function(data){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var result = JSON.parse(data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("input[name='csrf_test_name']").val(result['csrf']);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; });
随时随地看视频慕课网APP
我要回答