Yii 异步 jsonp 请求 [英] Yii Async jsonp request

查看:45
本文介绍了Yii 异步 jsonp 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Yii PHP 框架的新手,请耐心等待.

我需要发出跨域 JSONP 请求(来自非 yii 应用程序)以在 Yii 应用程序数据库中创建记录.创建后应通过 getVisit

返回 Application/json 内容

控制器:

公共函数 actionGetVisit($id){header('内容类型:应用程序/json');$visit = Visit::model()->findByPK((int)$id);echo CJSON::encode($visit);Yii::app()->end();}/*** 创建一个新模型.* 如果创建成功,浏览器将被重定向到查看"页面.*/公共函数 actionCreate(){$model=新访问;//如果需要 AJAX 验证,取消注释以下行//$this->performAjaxValidation($model);if(isset($_POST['访问'])){$model->attributes=$_POST['访问'];if($model->save())$this->redirect(array('getVisit','id'=>$model->id));}$this->render('create',array('模型'=>$模型,));}

表格:

<p class="note">带有 <span class="required">*</span> 的字段</p><div class="row"><label for="Visit_rvc_id" class="required">Rvc <span class="required">*</span></label><input name="Visit[rvc_id]" id="Visit_rvc_id" type="text" value="1">

<div class="row"><label for="Visit_zone" class="required">Zone <span class="required">*</span></label><input name="Visit[zone]" id="Visit_zone" type="text" value="1">

<div class="row"><label for="Visit_table" class="required">Table <span class="required">*</span></label><input name="Visit[table]" id="Visit_table" type="text" value="1">

<div class="row"><label for="Visit_seat" class="required">Seat <span class="required">*</span></label><input name="Visit[seat]" id="Visit_seat" type="text" value="1">

<div class="row"><label for="Visit_user_id" class="required">User <span class="required">*</span></label><input name="Visit[user_id]" id="Visit_user_id" type="text" value="1">

<div class="row"><label for="Visit_guest_name" class="required">客人姓名<span class="required">*</span></label><input size="60" maxlength="256" name="Visit[guest_name]" id="Visit_guest_name" type="text" value="1">

<div class="row"><label for="Visit_created" class="required">Created <span class="required">*</span></label><input name="Visit[created]" id="Visit_created" type="text" value="1">

<div class="行按钮"><input type="submit" name="yt0" value="Create">

</表单>

JS:

$('#visit-form').submit(function(event){警报('提交');event.preventDefault();var $form = $(this);$.ajax({网址:$(this).attr('action'),数据类型:'jsonp',类型:'POST',数据:$form.serialize()+'&ajax='+$form.attr('id'),成功:功能(数据,文本状态,XMLHttpRequest){alert('成功');if (data != null && typeof data == 'object'){$.each(data, function(key, value){$('#error').append(value);});}},错误:函数(XMLHttpRequest,textStatus,errorThrown){警报(错误抛出);警报('错误');}});返回假;});

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

GET http://host/index.php?r=visit/create&callback=jQuery15102636089683510363_1317230765087&Visit%5Brvc_id%5D=1&Visit%5Bzone%5D=1&Visit%;Visit%5Bseat%5D=1&Visit%5Buser_id%5D=1&Visit%5Bguest_name%5D=1&Visit%5Bcreated%5D=1&_=1317230785272 无法显示网址

响应设置为输出文本/

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

解决方案

这不是一个 Yii 的问题,更像是一个 JSONP 问题;您的 GetVisit 函数应如下所示:

公共函数 actionGetVisit($id){header('内容类型:应用程序/json');$visit = Visit::model()->findByPK((int)$id);$json = CJSON::encode($visit);回声 $_GET['回调'] .' (' . $json . ');';Yii::app()->end();}

jQuery 将全局临时函数附加到 window 对象,该函数在 JSONP 请求期间插入脚本时调用.jQuery 替换了 ?使用生成的函数名称(即 jsonp1232617941775)调用内联函数.您正在将该函数传递给 window 对象.

希望对您有所帮助,如果我在做一个项目时没有正确解释,请道歉.

I am new to the Yii PHP Framework so bear with me.

I need to make a cross-domain JSONP request(from a non-yii app) to create a record in the Yii apps DB. Upon creating it should return Application/json content via getVisit

The Controllers:

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,
    ));
}

The Form:

<form id="visit-form" action="http://host/index.php?r=visit/create" method="post">
            <p class="note">Fields with <span class="required">*</span> are required.</p>


            <div class="row">
                <label for="Visit_rvc_id" class="required">Rvc <span class="required">*</span></label>      <input name="Visit[rvc_id]" id="Visit_rvc_id" type="text" value="1">            </div>

            <div class="row">
                <label for="Visit_zone" class="required">Zone <span class="required">*</span></label>       <input name="Visit[zone]" id="Visit_zone" type="text" value="1">            </div>

            <div class="row">
                <label for="Visit_table" class="required">Table <span class="required">*</span></label>     <input name="Visit[table]" id="Visit_table" type="text" value="1">          </div>

            <div class="row">
                <label for="Visit_seat" class="required">Seat <span class="required">*</span></label>       <input name="Visit[seat]" id="Visit_seat" type="text" value="1">            </div>

            <div class="row">
                <label for="Visit_user_id" class="required">User <span class="required">*</span></label>        <input name="Visit[user_id]" id="Visit_user_id" type="text" value="1">          </div>

            <div class="row">
                <label for="Visit_guest_name" class="required">Guest Name <span class="required">*</span></label>       <input size="60" maxlength="256" name="Visit[guest_name]" id="Visit_guest_name" type="text"  value="1">         </div>

            <div class="row">
                <label for="Visit_created" class="required">Created <span class="required">*</span></label>     <input name="Visit[created]" id="Visit_created" type="text" value="1">          </div>

            <div class="row buttons">
                <input type="submit" name="yt0" value="Create"> </div>

        </form>

The 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;
        });

Upon Submission: It looks like its not erroring or hitting success. The response says:

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

The response is set to output text/

Does anyone know what this error means? The form submits perfectly without the js. But I just cant seem to get the ajax request working. I set it to 'jsonp' so cross-domain issues would go away. But I'm not sure if the Yii backend can handle the data sent as jsonp. Any help is appreciated!

解决方案

It's not really a Yii question, more of a JSONP issue; here's what your GetVisit function should look like:

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 attaches a global temporary function to the window object that is called when the script is inserted during a JSONP request. jQuery replaces the ? with a generated function name (ie jsonp1232617941775) that calls the inline function. You are passing that function to the window object.

Hope that helps, apologize if it's not correctly explained as I am working on a project.

这篇关于Yii 异步 jsonp 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆