Yii2中的Ajax + Controller Action [英] Ajax + Controller Action in Yii2

查看:55
本文介绍了Yii2中的Ajax + Controller Action的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,我正在尝试在用户输入数据并单击提交按钮时调用函数。我正在使用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 yii\helpers\Html;
use yii\widgets\LinkPager;

?>
<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 = \yii\web\Response::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);
       }
  });

这篇关于Yii2中的Ajax + Controller Action的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆