`
sailei1
  • 浏览: 126547 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Sencha Touch 2 Jsonp原理

阅读更多
JSONP是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实现跨域访问(这仅仅是JSONP简单的实现形式)。
//Sencha Touch 2 Jsonp 核心源码
Ext.define('Ext.data.JsonP', {
    alternateClassName: 'Ext.util.JSONP',

    /* Begin Definitions */

    singleton: true,


    /* End Definitions */

    /**
     * Number of requests done so far.
     * @private
     */
    requestCount: 0,

    /**
     * Hash of pending requests.
     * @private
     */
    requests: {},

    /**
     * @property {Number} [timeout=30000]
     * A default timeout (in milliseconds) for any JsonP requests. If the request has not completed in this time the failure callback will
     * be fired.
     */
    timeout: 30000,

    /**
     * @property {Boolean} disableCaching
     * `true` to add a unique cache-buster param to requests.
     */
    disableCaching: true,

    /**
     * @property {String} disableCachingParam
     * Change the parameter which is sent went disabling caching through a cache buster.
     */
    disableCachingParam: '_dc',

    /**
     * @property {String} callbackKey
     * Specifies the GET parameter that will be sent to the server containing the function name to be executed when the
     * request completes. Thus, a common request will be in the form of: 
     * `url?callback=Ext.data.JsonP.callback1`
     */
    callbackKey: 'callback',

    /**
     * Makes a JSONP request.
     * @param {Object} options An object which may contain the following properties. Note that options will take
     * priority over any defaults that are specified in the class.
     *
     * @param {String} options.url  The URL to request.
     * @param {Object} [options.params]  An object containing a series of key value pairs that will be sent along with the request.
     * @param {Number} [options.timeout]  See {@link #timeout}
     * @param {String} [options.callbackKey]  See {@link #callbackKey}
     * @param {String} [options.callbackName]  See {@link #callbackKey}
     *   The function name to use for this request. By default this name will be auto-generated: Ext.data.JsonP.callback1,
     *   Ext.data.JsonP.callback2, etc. Setting this option to "my_name" will force the function name to be
     *   Ext.data.JsonP.my_name. Use this if you want deterministic behavior, but be careful - the callbackName should be
     *   different in each JsonP request that you make.
     * @param {Boolean}  [options.disableCaching]  See {@link #disableCaching}
     * @param {String}   [options.disableCachingParam]  See {@link #disableCachingParam}
     * @param {Function} [options.success]  A function to execute if the request succeeds.
     * @param {Function} [options.failure]  A function to execute if the request fails.
     * @param {Function} [options.callback]  A function to execute when the request completes, whether it is a success or failure.
     * @param {Object}   [options.scope]  The scope in which to execute the callbacks: The "this" object for the
     *   callback function. Defaults to the browser window.
     *
     * @return {Object}  request An object containing the request details.
     */
    request: function(options){
        options = Ext.apply({}, options);

        //<debug>
        if (!options.url) {
            Ext.Logger.error('A url must be specified for a JSONP request.');
        }
        //</debug>

        var me = this,
            disableCaching = Ext.isDefined(options.disableCaching) ? options.disableCaching : me.disableCaching,
            cacheParam = options.disableCachingParam || me.disableCachingParam,
            id = ++me.requestCount,
            callbackName = options.callbackName || 'callback' + id,
            callbackKey = options.callbackKey || me.callbackKey,
            timeout = Ext.isDefined(options.timeout) ? options.timeout : me.timeout,
            params = Ext.apply({}, options.params),
            url = options.url,
            name = Ext.isSandboxed ? Ext.getUniqueGlobalNamespace() : 'Ext',
            request,
            script;

        params[callbackKey] = name + '.data.JsonP.' + callbackName;
        if (disableCaching) {
            params[cacheParam] = new Date().getTime();
        }

        script = me.createScript(url, params, options); //建立script标签实现跨域

        me.requests[id] = request = {
            url: url,
            params: params,
            script: script,
            id: id,
            scope: options.scope,
            success: options.success,
            failure: options.failure,
            callback: options.callback,
            callbackKey: callbackKey,
            callbackName: callbackName
        };

        if (timeout > 0) {
            request.timeout = setTimeout(Ext.bind(me.handleTimeout, me, [request]), timeout);
        }

        me.setupErrorHandling(request);
        me[callbackName] = Ext.bind(me.handleResponse, me, [request], true);//
        me.loadScript(request);
        return request;
    },

    /**
     * Abort a request. If the request parameter is not specified all open requests will be aborted.
     * @param {Object/String} request The request to abort.
     */
    abort: function(request){
        var requests = this.requests,
            key;

        if (request) {
            if (!request.id) {
                request = requests[request];
            }
            this.handleAbort(request);
        } else {
            for (key in requests) {
                if (requests.hasOwnProperty(key)) {
                    this.abort(requests[key]);
                }
            }
        }
    },

    /**
     * Sets up error handling for the script.
     * @private
     * @param {Object} request The request.
     */
    setupErrorHandling: function(request){
        request.script.onerror = Ext.bind(this.handleError, this, [request]);
    },

    /**
     * Handles any aborts when loading the script.
     * @private
     * @param {Object} request The request.
     */
    handleAbort: function(request){
        request.errorType = 'abort';
        this.handleResponse(null, request);
    },

    /**
     * Handles any script errors when loading the script.
     * @private
     * @param {Object} request The request.
     */
    handleError: function(request){
        request.errorType = 'error';
        this.handleResponse(null, request);
    },

    /**
     * Cleans up any script handling errors.
     * @private
     * @param {Object} request The request.
     */
    cleanupErrorHandling: function(request){
        request.script.onerror = null;
    },

    /**
     * Handle any script timeouts.
     * @private
     * @param {Object} request The request.
     */
    handleTimeout: function(request){
        request.errorType = 'timeout';
        this.handleResponse(null, request);
    },

    /**
     * Handle a successful response
     * @private
     * @param {Object} result The result from the request
     * @param {Object} request The request
     */
    handleResponse: function(result, request){
        var success = true;

        if (request.timeout) {
            clearTimeout(request.timeout);
        }

        delete this[request.callbackName];
        delete this.requests[request.id];

        this.cleanupErrorHandling(request);
        Ext.fly(request.script).destroy();
        //数据响应返回
        if (request.errorType) {
            success = false;
            Ext.callback(request.failure, request.scope, [request.errorType, request]);
        } else {
            Ext.callback(request.success, request.scope, [result, request]);
        }
        Ext.callback(request.callback, request.scope, [success, result, request.errorType, request]);
    },

    /**
     * Create the script tag given the specified url, params and options. The options
     * parameter is passed to allow an override to access it.
     * @private
     * @param {String} url The url of the request
     * @param {Object} params Any extra params to be sent
     * @param {Object} options The object passed to {@link #request}.
     */
    createScript: function(url, params, options) {
        var script = document.createElement('script');
        script.setAttribute("src", Ext.urlAppend(url, Ext.Object.toQueryString(params)));
        script.setAttribute("async", true);
        script.setAttribute("type", "text/javascript");
        return script;
    },

    /**
     * Loads the script for the given request by appending it to the HEAD element. This is
     * its own method so that users can override it (as well as {@link #createScript}).
     * @private
     * @param request The request object.
     */
    loadScript: function (request) {
        Ext.getHead().appendChild(request.script);//装载 来自服务器端的js 
    }
});


所以 服务端要这样写
boolean jsonP = false;
String cb = request.getParameter("callback"); //
传过来的 callback 参数 假如 Ext.data.JsonP.callback
if (cb != null) {
    jsonP = true;
    response.setContentType("text/javascript");
} else {
    response.setContentType("application/x-json");
}
Writer out = response.getWriter();
if (jsonP) {
    out.write(cb + "(");  //这拼一下js 数据
}
out.print(dataBlock.toJsonString());
if (jsonP) {
    out.write(");");
}


然后可以在页面上 输出
Ext.data.JsonP.callback({你的json 数据});
然后 主页面 script标签 加入这个 服务端的js, 实现跨域获取服务端数据
1
3
分享到:
评论

相关推荐

    Sencha touch 2.0 of JsonP

    下面将详细介绍如何在Sencha Touch 2.0中使用JsonP以及相关文件的作用: 1. **MakeToJsonP.aspx 和 MakeToJsonP.aspx.cs**: 这两个文件可能是ASP.NET Web应用程序中的一个页面和对应的后端代码文件。在JsonP的...

    touch-docs-2.2.1.zip(senchaTouch 离线API参考文档)

    4. **用户手册**:全面介绍Sencha Touch的架构、工作原理以及最佳实践。 将这个文档部署到Tomcat的webAPP目录下,意味着你可以通过Web服务器访问这些离线文档,无需网络连接,这对于开发者来说非常方便,特别是在...

    sencha touch中文翻译文档

    这个"Sencha Touch中文翻译文档"是针对Sencha Touch 2(ST2)的详细教程和指南,旨在帮助中国开发者更轻松地理解和运用这一框架。 在入门基础部分,文档可能涵盖了以下内容: 1. **安装与设置**:如何下载Sencha ...

    sencha touch grid

    Sencha Touch Grid是一款专为移动设备设计的数据网格组件,它属于Sencha Touch框架的一部分。Sencha Touch是一个流行的JavaScript库,用于构建高性能、跨平台的触摸友好型移动应用程序。Grid组件在移动应用中常用于...

    Sencha Touch-2.4.2

    Sencha Touch 2.4.2 是一个专为移动设备设计的前端开发框架,它允许开发者构建高性能、跨平台的触控式Web应用程序。这款框架是Sencha公司推出的,目标是帮助开发者创建与原生应用体验相媲美的HTML5应用。在Sencha ...

    How to Create a Sencha Touch 2 App source code

    Sencha Touch 2 是一款...记住,学习Sencha Touch 2不仅仅是复制代码,更重要的是理解其背后的原理,以便在实际项目中灵活运用。在实践中不断迭代和优化,你的技能会逐渐提升,从而能够构建出更复杂、性能更优的应用。

    Sencha_touch2详细资料整理一

    在压缩和gzip处理后,Sencha Touch 2 的库大小约为80KB,通过精简不必要的组件,还能进一步减小其体积,使得在移动设备上快速加载成为可能。 该框架特别强调对顶级设备的支持,包括Android和iOS。在Beta版本中,...

    sencha touch 例子 list 使用 代码

    本教程将深入探讨`List`组件的使用方法,以及如何在Sencha Touch 2中实现一个示例。 首先,`List`组件是基于Ext.dataview.List构建的,它提供了强大的数据绑定功能,能够动态地根据数据源更新视图。要创建一个`List...

    senchatouch通过Ajax连接ashx

    然而,Sencha Touch提供了一些绕过这一限制的替代方法,如跨域请求(Cross-Domain Requests)和JSONP。 Ext.Ajax.request允许开发者设置多种选项,包括请求方法(GET、POST、PUT、DELETE)、发送HTTP头信息,以及在...

    sencha-touch-2.1.1-gpl.zip

    Sencha Touch 2.1.1版本在前一版本的基础上进行了优化和增强,提高了性能,提供了更多的功能和组件。以下是一些关键知识点: 1. **响应式设计**:Sencha Touch 2.1.1支持各种屏幕尺寸和设备类型,能自动调整布局以...

    sencha-touch-2.0.0-pr1.zip

    Sencha Touch 2.0.0 PR1 是一个早期版本的Sencha Touch框架,用于构建移动Web应用程序。这个预发布版本(PR1)是开发者在正式版本发布前获取新功能和改进的一个机会。Sencha Touch是一个JavaScript库,专门设计用于...

    kitechen_app_sencha_touch

    6. **本地存储和远程数据同步**:通过Store和Proxy,Sencha Touch 支持离线数据存储和与服务器的数据交换,如JSONP、Ajax等。 在“kitchen_app_sencha_touch”的例子中,我们可能看到以下几个方面: 1. **应用程序...

    sencha-touch-2.2.1-commercial

    2. **组件库**:Sencha Touch包含丰富的UI组件,如表格、图表、下拉菜单、按钮、滑块、日期选择器等,这些组件都经过优化,确保在移动设备上的性能和用户体验。通过这些组件,开发者可以快速构建功能丰富的应用界面...

    Ext.ux.proxy.ProxyCache:Sencha Touch 2双存储代理

    包括带有缓存功能的默认Sencha Touch 2服务器代理(Ajax,JsonP和REST)的扩展版本。 安装 克隆存储库或使用上面的“ Zip”按钮下载它。 将ux文件夹放在应用程序的根目录中(与index.html和app.js放在同一文件夹中...

    NotesApp-ST2-demo

    《NotesApp-ST2-demo:Sencha Touch 2.0 框架在移动应用开发中的实践》 在当今移动互联网盛行的时代,开发跨平台的移动应用程序成为开发者的重要任务。"NotesApp-ST2-demo"是一个基于Sencha Touch 2.0框架的示例...

    sencha相关文档

    它包含两个主要产品:Ext JS和Sencha Touch。Ext JS 适用于桌面Web应用,而Sencha Touch则专注于移动设备的应用开发。这些文档集合可能包含了关于这两个产品的详细信息,帮助开发者理解和掌握Sencha的相关技术。 在...

    用HTML5开发移动应用.pdf

    例如,"使用Sencha Touch开发新浪微博iPhone界面"的示例展示了如何利用Sencha Touch的原生UI组件来模仿iPhone的界面设计,这些组件包括导航栏、表格视图、表单元素等,使得开发者可以轻松创建出具有吸引力的移动应用...

    移动开发框架

    2. **数据集成**:支持AJAX、JSONP和YQL进行数据绑定,利用localStorage进行离线数据保存。 3. **Animator**:一个桌面应用程序,用于为WebKit浏览器和触摸屏移动设备创建CSS3动画,以实现丰富的设备体验。 **开发...

Global site tag (gtag.js) - Google Analytics