是的,我只想要一个非常简单的 ajax 请求来让它工作。我是新的 yii 2.0 框架,你看到了。
在我看来 index.php:
function sendFirstCategory(){
var test = "this is an ajax test";
$.ajax({
url: '<?php echo \Yii::$app->getUrlManager()->createUrl('cases/ajax') ?>',
type: 'POST',
data: { test: test },
success: function(data) {
alert(data);
}
});
}
现在,当我调用它时,我假设它应该转到我的 CasesController 以执行名为 actionAjax 的操作。
public function actionAjax()
{
if(isset($_POST['test'])){
$test = "Ajax Worked!";
}else{
$test = "Ajax failed";
}
return $test;
}
编辑::
好的,很好,所以这到这里为止。我取回了 $test 的新值弹出的警报。但是,我希望能够在 php 中访问此值,因为最终我将从数据库中访问数据,并且想要查询和执行其他各种操作。
那么我现在如何在 php 中使用这个变量,而不仅仅是弹出 alert()?
最佳答案
以下是如何访问 Controller 中的帖子数据:
public function actionAjax()
{
if(isset(Yii::$app->request->post('test'))){
$test = "Ajax Worked!";
// do your query stuff here
}else{
$test = "Ajax failed";
// do your query stuff here
}
// return Json
return \yii\helpers\Json::encode($test);
}
关于ajax - 在 Yii 2.0 中发出 Ajax 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29347905/