Yii异步jsonp请求

我是Yii PHP Framework的新手,所以请耐心等待。

我需要创建跨域JSONP请求(来自非yii应用程序)以在Yii apps DB中创建记录。 创建后,它应该通过getVisit返回Application / json内容

控制器:

public function actionGetVisit($id) { header('Content-type: application/json'); $visit = Visit::model()->findByPK((int)$id); echo CJSON::encode($visit); Yii::app()->end(); } /** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model=new Visit; // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['Visit'])) { $model->attributes=$_POST['Visit']; if($model->save()) $this->redirect(array('getVisit','id'=>$model->id)); } $this->render('create',array( 'model'=>$model, )); } 

表格:

 

Fields with * are required.

JS:

 $('#visit-form').submit(function(event) { alert('submit'); event.preventDefault(); var $form = $(this); $.ajax({ url: $(this).attr('action'), dataType: 'jsonp', type: 'POST', data : $form.serialize()+'&ajax='+$form.attr('id'), success: function(data, textStatus, XMLHttpRequest) { alert('success'); if (data != null && typeof data == 'object'){ $.each(data, function(key, value){ $('#error').append(value); }); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown); alert('error'); } }); return false; }); 

提交后:看起来它没有错误或成功。 回复说:

 GET http://host/index.php?r=visit/create&callback=jQuery15102636089683510363_1317230765087&Visit%5Brvc_id%5D=1&Visit%5Bzone%5D=1&Visit%5Btable%5D=1&Visit%5Bseat%5D=1&Visit%5Buser_id%5D=1&Visit%5Bguest_name%5D=1&Visit%5Bcreated%5D=1&_=1317230785272 The URL can't be shown 

响应设置为输出文本/

有谁知道这个错误意味着什么? 表格在没有js的情况下提交完美。 但我似乎无法让ajax请求正常工作。 我将其设置为’jsonp’,因此跨域问题将会消失。 但我不确定Yii后端是否可以处理以jsonp发送的数据。 任何帮助表示赞赏!

这不是一个Yii问题,更多的是JSONP问题; 这是你的GetVisit函数应该是什么样子:

 public function actionGetVisit($id) { header('Content-type: application/json'); $visit = Visit::model()->findByPK((int)$id); $json = CJSON::encode($visit); echo $_GET['callback'] . ' (' . $json . ');'; Yii::app()->end(); } 

jQuery将一个全局临时函数附加到在JSONP请求期间插入脚本时调用的窗口对象。 jQuery取代了? 使用生成的函数名称(即jsonp1232617941775)来调用内联函数。 您正在将该函数传递给window对象。

希望有所帮助,如果我正在处理项目时没有正确解释,请道歉。