我在控制器中发送数据,其中包含具有如下格式的日期周日 3月 08 2015 00:00:00 GMT+0000我的控制器中的代码是
public function actionSaveajaxevent() {
if (isset($_POST['Event']) && isset($_POST['datetime']) && isset($_POST['start']) && isset($_POST['end'])) {
$start = $_POST['start'];
$end = $_POST['end'];
$title = $_POST['Event']['title'];
if ($model->save()) {
$array = ['title' => $model->title, 'start' => $start, 'end' => $end];
echo json_encode($array);
}
} else {
print_r($model->getErrors());
}
}
我想在我的视图中获取标题、开始和结束。 视图中的 jquery 函数是
<script>
$(document).ready(function () {
$('#w1').submit(function (event) {
event.preventDefault();
var postData = $(this).serialize();
$.ajax({
type: 'post',
dataType: "json",
data: postData,
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('site/saveajaxevent'); ?>',
success: function (data) {
var response = $.parseJSON(data);
console.log(response.title);
return false;
},
});
event.preventDefault();
return false;
});
});
</script>
下面是我的控制台中的错误
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
返回 JSON.parse( data + " );
提前致谢
尝试在 Ajax 代码中添加检查来自服务器的响应,是否正确:
<script>
$(document).ready(function () {
$('#w1').submit(function (event) {
event.preventDefault();
var postData = $(this).serialize();
$.ajax({
type: 'post',
dataType: "json",
data: postData,
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('site/saveajaxevent'); ?>',
success: function (data) {
alert(data); //before parse the JSON first alert the response
//var response = $.parseJSON(data);
//console.log(response.title);
return false;
},
});
event.preventDefault();
return false;
});
});
</script>