我在jQuery脚本中调用AJAX请求。我已经在其中创建了控制器(AjaxController)和方法actionRequest。JQuery发送此请求:
jQuery.ajax({
url: location.origin + '/web/index.php?r=ajax/request',
async: false,
type: 'POST',
data: {'param': 32},
dataType: 'json',
success: function(data) {result = data}
});
这个代码在控制器的脚本中:
public function actionRequest() {
$param = Yii::$app->request->post('param');
echo json_encode($param);
}
控制器已接受此选项并将其发回。JavaScript在"alert()"的帮助下显示此选项(结果)。如果我用GET方法发送它,那么一切都正常,窗口显示"32"。但如果我将此请求更改为"POST",则窗口显示"未定义"。如果我将请求发送到我的PHP脚本(路径:/web.PHP),那么一切都能正常工作。如果我将从我的控制器中删除所有代码并只留下:
<?php
$param = $_POST['param'];
echo json_encode($param);
?>
并直接询问脚本,然后所有操作都正确。。。
当我使用AJAX方法POST时,所有迹象都表明框架中存在错误。因为如果我在我的控制器里写这个代码:
$root = $_SERVER['DOCUMENT_ROOT'];
$file = fopen($root . '/text.txt', 'w');
fwrite($file, '1');
fclose($file);
然后我发送GET请求,代码完成并在站点的根目录中创建文件。但若我将请求更改为POST,那个么就不会创建文件。
我的控制器来源:
<?php
namespace app'controllers;
use Yii;
use yii'filters'AccessControl;
use yii'web'Controller;
use yii'filters'VerbFilter;
use app'models'LoginForm;
use app'models'ContactForm;
use yii'helpers'Html;
class AjaxController extends Controller {
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actions() {
return [
'error' => [
'class' => 'yii'web'ErrorAction',
],
'captcha' => [
'class' => 'yii'captcha'CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionIndex() {
return '';
}
public function actionRequest() {
$param = Yii::$app->request->post('param');
echo json_encode($param);
}
}
?>
我的URL管理员:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'suffix' => '/',
'rules' => [
'' => 'site/index',
'register' => 'site/register'
]
]
根据您的UrlManager设置,尝试将您的ajax url更改为此url。
url: location.origin + '/ajax/request/',
只需附加控制器名称、操作名称和尾部正斜杠。
原因是
- 您将
enablePrettyUrl
设置为true
showScriptName
至false
suffix
至/
我已经测试过了,它适用于GET
和POST
类型。
只需记住更改函数即可获得相应的GET
和POST
参数。