Yii2 中的 Ajax + 控制器动作

2022-01-07 00:00:00 jquery php javascript ajax yii2

我是编程新手,我试图在用户输入数据并单击提交按钮时调用一个函数.我正在使用 Yii2 并且我不熟悉 Ajax.我尝试开发一个函数,但没有调用我的控制器操作.

I'm new to programming, and I'm trying to call a function when the user inputs data and clicks submit button. I'm using Yii2 and I'm not familiar with Ajax. I tried developing a function, but my controller action isn't called.

这是我正在尝试的示例代码:

Here is the example code I'm trying:

views/index.php:

views/index.php:

<script>
    function myFunction()
    {
        $.ajax({
            url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
           type: 'post',
           data: {searchname: $("#searchname").val() , searchby:$("#searchby").val()},
           success: function (data) {
              alert(data);

           }

      });
    }
</script>

<?php
use yiihelpersHtml;
use yiiwidgetsLinkPager;

?>
<h1>Supermarkets</h1>
<ul>

<select id="searchby">
    <option value="" disabled="disabled" selected="selected">Search by</option>
    <option value="Name">Name</option>
    <option value="Location">Location</option>
</select>

<input type="text" value ="" name="searchname", id="searchname">
<button onclick="myFunction()">Search</button>
<h3> </h3>

控制器:

public function actionSample(){         
     echo "ok";
}

我的问题是,当我单击搜索"按钮时什么也没有发生,当我尝试调试它时,调试器不运行任何代码!

My problem is that when I click on the Search button nothing happens, and when I try to debug it, the debugger runs no code!

推荐答案

这是您可以根据需要修改的示例

This is sample you can modify according your need

public function actionSample()
{
if (Yii::$app->request->isAjax) {
    $data = Yii::$app->request->post();
    $searchname= explode(":", $data['searchname']);
    $searchby= explode(":", $data['searchby']);
    $searchname= $searchname[0];
    $searchby= $searchby[0];
    $search = // your logic;
    Yii::$app->response->format = yiiwebResponse::FORMAT_JSON;
    return [
        'search' => $search,
        'code' => 100,
    ];
  }
}

如果这会成功,您将在 Ajax 成功块中获得数据.查看浏览器控制台.

If this will success you will get data in Ajax success block. See browser console.

  $.ajax({
       url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
       type: 'post',
       data: {
                 searchname: $("#searchname").val() , 
                 searchby:$("#searchby").val() , 
                 _csrf : '<?=Yii::$app->request->getCsrfToken()?>'
             },
       success: function (data) {
          console.log(data.search);
       }
  });

相关文章