我在我的 View 文件中使用了以下按钮(不要注意第二个按钮,但我只是想告诉你为什么我不使用普通表单提交):
<?php echo CHtml::Button('Search Symptom(s)', array('id'=>'search')); ?>
<?php echo CHtml::Button('Add Another Symptom to Search', array('id'=>'addSymptom')); ?>
当用户单击按钮时,此 javascript 运行(它在 document.ready 函数中)
$('#search').click(function()
{
//create new symptom in javascript
var newSymptom =
{
symptomCode: $('#symptomToBeSearchedCode').val(),
dateSymptomFirstSeen: $('#dateSymptomSeen').val(),
symptomTitle: $('#symptomToBeSearchedTitle').val()
};
//pass new symptom into symptomsList array
symptomsList.push(newSymptom);
//make ajax call to server
$.ajax({
type:'POST',
url: '/mysymptomsbook/index.php?r=symptomhistory/search',
data:{symptomsList: symptomsList} ,
dataType:'html'
});
});
symptomsList 是一个包含 JS 对象的数组
这是我的 Controller 操作中的代码:
if(isset($_POST['symptomsList']))
{
foreach($_POST['symptomsList'] as $symptom)
{
//populate symptom search model attributes with user id, current date, and form input
$newSymptom = new Symptomhistory;
$newSymptom->setAttributes(array(
'user_id'=>Yii::app()->user->id,
'dateSearched'=>date('Y-m-d'),
'symptomCode'=>$symptom['symptomCode'],
'dateSymptomFirstSeen'=>$symptom['dateSymptomFirstSeen'],
'symptomTitle'=>$symptom['symptomTitle'],
));
//save search history
$newSymptom->save();
//add into the searched for symptoms code the latest code
array_push($symptomCodes, strval($symptom['symptomCode']));
}
$this->redirect(array('disease/index'));
}
我计划使用重定向将 $symptomCodes 数组发送到其他 Controller 操作(DiseasesController 和 actionIndex),但即使不传递任何内容,重定向也不起作用。模型会正常保存到我的数据库中。
谁知道哪里出了问题?我认为它与 Ajax 有关,因为它正在等待响应,但我希望我的 Controller 改为重定向。一如既往的任何帮助,我们将不胜感激:)
最佳答案
我也遇到过类似的问题,推荐你去官方论坛看看这个话题: redirect not working when called via Ajax-Request
请参阅主题中的最后一个答案。
关于javascript - 在 ajax 调用不起作用后 Yii 从 Controller 操作重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24230781/