【发布时间】:2016-03-28 03:41:43
【问题描述】:
那么问题来了:
尝试使用 .ajax 进行 ajax 调用。但是,某个地方出了点问题,因为我的控制器没有重定向到好的视图文件并且我的页面上没有显示任何内容。
这里是ajax调用发生的地方
$('#validate').on('click',function(){
var data = []; // data container
// collect all the checked checkboxes and their associated attributes
$("table#subsection_table input[type='checkbox']:checked").each(function(){
data.push({
subsectionid : $(this).val(),
sectionid : $(this).data('sectionid'),
year : $(this).data('year')
})
});
// JSON it so that it can be passed via Ajax call to a php page
var data = JSON.stringify(data);
$.ajax({
url : "<?php echo Yii::app()->createAbsoluteUrl("scheduler/AjaxExample"); ?>",
type: "POST",
data : "myData=" + data,
success : function()
{
alert("in success");
$("#ajax-results").html(data);
$("#ajax-results").dialog({ width: 500, height: 500})
},
error: function()
{
alert("there was an error")
}
})
console.log(JSON.stringify(data));
$('#dialog').html(data).dialog({ width: 500, heigh: 500});
});
现在这是我的控制器代码:
public function actionAjaxExample()
{
$post_data = $_POST['myData'];
$this->renderPartial('_ajax', array(
'data'=> $post_data,
)
);
}
尝试重定向到 _ajax 视图文件:
<?php
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
echo "HI FROM BACKEND! here's what you gave to PHP: <br>";
print_r($data);
?>
所以我显然做错了,但是......我似乎找不到哪里,因为 ajax 调用确实发生了(至少在我的 #validate on click 事件中)。但是,最后一个视图文件没有显示它的警告框或“来自后端的问候”。
【问题讨论】:
-
你能检查一下你的代码给出的 url:"createAbsoluteUrl("scheduler/AjaxExample"); ?>" 是否正确?
-
同样,如果您定义了启用了 accessControl 的 filter(),则您的方法 AjaxExample() 必须是可访问的。在您的 js 代码中,您没有将响应数据传递给成功函数,请执行以下操作:
success : function( response ) { alert("in success"); alert(response); ... },以便您可以轻松检查服务器响应。 -
哦,我忘了做函数(数据)。对于访问控制,我读到只有当我在我的文件中使用 accessRules() 时我才不是(我不认为我是无论如何,我对 Yii 相当陌生)。至于 AjaxExample,它位于 Protected -> Controller -> SchedulerController -> actionAjaxExample 下。否则它会给我一个 404 url not found in my console no?
-
还要检查控制器代码,确保 php 如何接收数据,使用类似:
public function actionAjaxExample() { print_r($_POST); }这样您就可以正确使用您发送的数据。 -
try
$this->renderPartial('_viewfile', $data, false, true);尝试为处理后的输出设置第四个参数为真