简体   繁体   English

如何通过yii2框架中的特定ID通过Ajax从数据库检索数据

[英]How to retrieve data from database through ajax against specific id in yii2 framwork

I want to send ajax object from _form.php file to retrieve data from database against object value. 我想从_form.php文件发送ajax对象,以针对对象值从数据库中检索数据。

The ajax url file is regAjax.php , but the url is not found: 该ajax网址文件是regAjax.php ,但是找不到该网址:

Error 404 found in console 在控制台中发现错误404

_form.php: _form.php这个:

<?= $form->field($vehicle, 'vehicleRegistrationNumber')->textInput(['maxlength' => true, 'id'=> 'regNum']) ?>

Ajax code: Ajax代码:

$.ajax({
    type: 'POST',
    cache: false,
    data: { regNum: regNum },
    url: "<?php echo Url::toRoute('appointments/regAjax.php')?>",
    success: function(response) {
        console.log('success');
    }
});

AppointmentsController: AppointmentsController:

public function actionRegAjax()
{
   if(Yii::$app->request->isAjax) {
       $data = Yii::$app->request->post();
   } 
}

regAjax.php: regAjax.php:

<?php
$regNum = $_POST['regNum'];
echo json_encode($regNum);
?>

As far as I understand that you want to retrieve data from actionRegAjax() function which is inside AppointmentsController . 据我了解,你想要从actionRegAjax()函数,它是内部AppointmentsController数据。

Yii2 routing style works like below; Yii2路由样式如下所示;

controller name and function name seperated by (/), and if any letter starts with uppercase then you have to seperate it with (-), so all you need to do is change URL in your ajax to 控制器名称和函数名称,以(/)分隔,如果任何字母以大写字母开头,则必须以(-)分隔,因此您所需要做的就是将ajax中的URL更改为

url: "appointments/reg-ajax",
$.ajax({
    type: 'POST',
    cache: false,
    data: { regNum: regNum },
    url: "<?= Url::to(['appointments/reg-ajax'])?>",
    success: function(response) {
        console.log(response);
    }
});

Your access to controller Action was not appropriate. 您对控制器操作的访问权限不合适。 Find the above appropriate method to do so. 找到上述合适的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM