src/cm/media/js/lib/yui/yui_3.10.3/docs/jsonp/index.html
author Yves-Marie Haussonne <ymh.work+github@gmail.com>
Fri, 09 May 2014 18:35:26 +0200
changeset 656 a84519031134
parent 525 89ef5ed3c48b
permissions -rw-r--r--
add link to "privacy policy" in the header test

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JSONP</title>
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,700,400italic,700italic">
    <link rel="stylesheet" href="../../build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/css/main.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">
    <script src="../../build/yui/yui-min.js"></script>
    
</head>
<body>
<!--
<a href="https://github.com/yui/yui3"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub"></a>
-->
<div id="doc">
    <div id="hd">
        <h1><img src="http://yuilibrary.com/img/yui-logo.png"></h1>
    </div>
    
        <a href="#toc" class="jump">Jump to Table of Contents</a>
    

            <h1>JSONP</h1>
    <div class="yui3-g">
        <div class="yui3-u-3-4">
            <div id="main">
                <div class="content"><div class="intro component">
        <p>
            The JSONP Utility is a specialized API for communicating with web
            services that provide JSON responses wrapped in a callback
            function.  A typical JSONP request URL might look like
            &quot;http://example.com/service.php?callback=handleData&quot; and
            receive a text response in the form of
            <code>handleData({"records":[....]});</code>.
        </p>

        <p>
            The nature of YUI 3's sandbox model complicates JSONP transactions
            because JSONP relies on a global access point to process the
            response, but YUI 3 implementation code is typically wrapped in a
            <code>use(...)</code> callback and is therefore not globally
            accessible.  The JSONP module provides a proxy system for
            channeling JSONP responses back into your YUI instance sandbox.
        </p>

        <p>
            <strong>Security Note:</strong> JSONP is an inherently unsecure
            communication method, since it involves the transfer of unvalidated
            JavaScript.  It is by convention alone that the format is
            associated with JSON, but in reality, the response can include any
            arbitrary JavaScript, potentially opening your page to attack.
            <em>Be cautious about which services you communicate with via
            JSONP</em>.  For safe JSON communication, use the <a
            href="../json/index.html">JSON module</a> in
            conjunction with the <a
            href="../io/index.html">IO module</a> wherever
            possible.
        </p>
</div>

<h2 id="getting-started">Getting Started</h2>

<p>
To include the source files for JSONP and its dependencies, first load
the YUI seed file if you haven't already loaded it.
</p>

<pre class="code prettyprint">&lt;script src=&quot;http:&#x2F;&#x2F;yui.yahooapis.com&#x2F;3.10.3&#x2F;build&#x2F;yui&#x2F;yui-min.js&quot;&gt;&lt;&#x2F;script&gt;</pre>


<p>
Next, create a new YUI instance for your application and populate it with the
modules you need by specifying them as arguments to the <code>YUI().use()</code> method.
YUI will automatically load any dependencies required by the modules you
specify.
</p>

<pre class="code prettyprint">&lt;script&gt;
&#x2F;&#x2F; Create a new YUI instance and populate it with the required modules.
YUI().use(&#x27;jsonp&#x27;, &#x27;jsonp-url&#x27;, function (Y) {
    &#x2F;&#x2F; JSONP is available and ready for use. Add implementation
    &#x2F;&#x2F; code here.
});
&lt;&#x2F;script&gt;</pre>


<p>
For more information on creating YUI instances and on the
<a href="http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_use"><code>use()</code> method</a>, see the
documentation for the <a href="../yui/index.html">YUI Global Object</a>.
</p>


<h2 id="using">Using the JSONP Utility</h2>

<h3 id="basic">Instantiation and the <code>Y.jsonp</code> method</h3>

<p>
    The JSONP utility provides the <code>Y.jsonp(url, callback)</code> method
    for single transactions as well as a <code>Y.JSONPRequest</code> class to
    manage reusable connections.
</p>


<p>
    The first argument to either the <code>Y.jsonp</code> method or the
    <code>Y.JSONPRequest</code> constructor is the URL of the JSONP service,
    and the second is a callback function or <a href="#config">configuration
    object</a> that contains a callback function.  When the service responds
    with the data, the callback will be executed with the response data as the
    first parameter.
</p>


<p>
    In place of the JSONP callback name in the URL, include the string
    &quot;{callback}&quot;.  This placeholder will be used for a proxy function
    that will route the data to your callback.
</p>


<pre class="code prettyprint">&#x2F;&#x2F; instead of service.php?callback=handleJSONP
var url = &quot;http:&#x2F;&#x2F;example.com&#x2F;service.php?callback={callback}&quot;;

function handleJSONP(response) {
    &#x2F;&#x2F; response is a JavaScript object. No parsing necessary
    Y.one(&quot;#output&quot;).setHTML(response.outputHTML);
}

Y.jsonp(url, handleJSONP);

&#x2F;&#x2F; or
var service = new Y.JSONPRequest(url, handleJSONP);
service.send();</pre>


<h4 id="timing">Sending JSONP requests</h4>

<p>
    <code>Y.jsonp(url, callback)</code> will dispatch the request immediately.
    JSONPRequest instances will dispatch the request each time their
    <code>send()</code> method is called.
</p>


<pre class="code prettyprint">&#x2F;&#x2F; request sent immediately
Y.jsonp(url, handleJSONP);

&#x2F;&#x2F; No request sent
var service = new Y.JSONPRequest(url, handleJSONP);

&#x2F;&#x2F; ...until now
service.send();

&#x2F;&#x2F; ...and now again
service.send();</pre>


<p>
    <code>Y.jsonp(url, callback)</code> is a convenience wrapper to instantiate
    a JSONPRequest instance and call its <code>send()</code> method.
</p>


<p>
    This will generate a request to a URL like this one (note that the
    <code>{callback}</code> placeholder has been replaced with a dynamically
    generated callback name):
</p>


<pre class="code prettyprint">http:&#x2F;&#x2F;example.com&#x2F;service.php?callback=YUI.Env.JSONP.yui_3_3_0_1_1294184187597423</pre>


<p>
    The server will then be expected to respond with a JavaScript value wrapped
    in a call to that function, like this:
</p>

<pre class="code prettyprint">YUI.Env.JSONP.yui_3_3_0_1_1294184187597423({&quot;foo&quot;:&quot;bar&quot;});</pre>


<h3 id="config">Configuring the connection</h3>

<p>
    The second argument to either <code>Y.jsonp</code> or the
    <code>Y.JSONPRequest</code> constructor can be a success callback function
    or for more control, it can be a configuration object.  The supported keys
    of this object are:
</p>


<table>
    <thead>
        <tr>
            <th>Property</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>timeout</td>
            <td>
                This value, defined as milliseconds, is a time threshold for
                the transaction (e.g., <code>{ timeout: 2000 }</code> ). When
                this limit is reached, the transaction's
                <code>on.timeout</code> callback will be executed if
                supplied.
            </td>
        </tr>
        <tr>
            <td>context</td>
            <td>
                Defines what will be &quot;<code>this</code>&quot; in the
                callbacks.  If undefined, the default will be the JSONPRequest
                instance.
            </td>
        </tr>
        <tr>
            <td>args</td>
            <td>
                An array of additional arguments that will be passed to the
                callbacks as second, third, and so on arguments.
            </td>
        </tr>
        <tr>
            <td>on</td>
            <td>
                <p>
                    <strong>Required</strong>. This object defines the
                    callbacks to be used for the transaction.  At least an
                    <code>on.success</code> handler must be defined.
                </p>
                <ul>
                    <li>success (<strong>required</strong>)</li>
                    <li>failure</li>
                    <li>timeout</li>
                </ul>
            </td>
        </tr>
        <tr>
            <td>format</td>
            <td>
                Preprocessor function to stitch together the supplied URL
                (first argument), the proxy function name (internally
                generated), and any additional arguments passed to
                <code>send()</code>.  See <a href="#format">Customizing the
                JSONP URL</a> for more detail.
            </td>
        </tr>
    </tbody>
</table>

<p>
    This is an example of a configuration object, with a set of properties
    defined.
</p>

<pre class="code prettyprint">var url     = &quot;http:&#x2F;&#x2F;example.com&#x2F;service.php?callback={callback}&quot;,
    service = new Y.JSONPRequest(url, {
        on: {
            success: MyApp.handleJSONP,
            timeout: MyApp.handleTimeout
        },
        context: MyApp
        timeout: 3000,          &#x2F;&#x2F; 3 second timeout
        args: [new Date(), 100] &#x2F;&#x2F; e.g. handleJSONP(data, date, number)
    });

service.send();

&#x2F;&#x2F; or
Y.jsonp(url, {
    on: {
        success: MyApp.handleJSONP,
        timeout: MyApp.handleTimeout
    },
    context: MyApp
    timeout: 3000,          &#x2F;&#x2F; 3 second timeout
    args: [new Date(), 100] &#x2F;&#x2F; e.g. handleJSONP(data, date, number)
});</pre>


<h3 id="url">Parsing the callback from the URL</h3>

<p>
    An extension for the <code>jsonp</code> module is the
    <code>jsonp-url</code> module which provides a few additional features.
</p>


<ol>
    <li>
        If you have a global function or a function available from the YUI
        instance (e.g. <code>Y.MyApp.handleJSONP</code>), you can include the
        name in the URL and omit the second parameter entirely.
    </li>
    <li>
        The URL passed as the first parameter need not include the
        &quot;{callback}&quot; string.  If it is not found, it will look for
        &quot;callback=&quot;, then fall back to adding the query parameter
        onto the URL.
    </li>
</ol>

<pre class="code prettyprint">Y.MyApp.handleJSONP = function (data) {
    Y.one(&quot;#output&quot;).setHTML(data.outputHTML);
};

Y.jsonp(&quot;http:&#x2F;&#x2F;example.com&#x2F;service.php?callback=Y.MyApp.handleJSONP&quot;);

&#x2F;&#x2F; or
Y.jsonp(&quot;http:&#x2F;&#x2F;example.com&#x2F;service.php&quot;, {
    context: Y.MyApp,
    on: {
        success: Y.MyApp.handleJSONP,
        failure: Y.MyApp.handleFailure
    }
});</pre>


<h3 id="format">Customizing the JSONP URL</h3>

<p>
    The default URL formatter simply replaces the &quot;{callback}&quot;
    placehold with the name of the generated proxy function.  If you want to
    customize the URL generation process, you can provide a <code>format</code>
    function in the configuration.  The function will receive the configured
    URL (with &quot;{callback}&quot; placeholder), the string name of the proxy
    function, and any additional arguments that were passed to
    <code>send()</code>.
</p>

<pre class="code prettyprint">&#x2F;&#x2F; Our custom formatter will expect a URL with an additional placeholder for
&#x2F;&#x2F; username that must be supplied in send(&quot;bill&quot;);
&#x2F;&#x2F; e.g. http:&#x2F;&#x2F;example.com&#x2F;bill&#x2F;json?fn=YUI.Env.JSONP._12345
function prepareJSONPUrl(url, proxy, username) {
    return Y.Lang.sub(url, {
        callback: proxy,
        name: username || &quot;user&quot;
    });
}

var url = &quot;http:&#x2F;&#x2F;example.com&#x2F;{name}&#x2F;json?fn={callback}&quot;;

var service = new Y.JSONPRequest(url, {
        format: prepareJSONPUrl,
        on: {
            success: handleJSONP
        }
    });

service.send(&quot;apipkin&quot;);
service.send(&quot;tivac&quot;);
service.send(&quot;razass&quot;);</pre>


<h2 id="issues">Known Issues</h2>

<ul>
    <li>
        Unlike the XMLHttpRequest calls generated by the IO utility, JSONP
        requests can't be aborted, since they rely on dynamic script insertion
        (which provides less low-level control than XHR). Keep this in mind
        when deciding which method to use.
    </li>

    <li>
        Since most browsers don't enforce execution order for dynamically
        inserted scripts, JSONP callbacks may not be called in the same order
        that the requests were sent. On the other hand, some browsers
        <em>do</em> enforce execution order, so in these browsers a slow
        request may block the execution of subsequent JSONP callbacks.
    </li>
    <li>
        In WinJS (Windows 8 application mode), JSONP is not supported
        due to the security measures enforced in that environment. Making 
        a JSONP request requires a remote script tag which is prohibited.
        An alternative is to use the YQL module to query a YQL table that
        can return the data that you need. The YQL module is supported in
        this environment because it uses native <code>XMLHttpRequest</code> to fetch it's data.
    </li>
</ul>
</div>
            </div>
        </div>

        <div class="yui3-u-1-4">
            <div class="sidebar">
                
                    <div id="toc" class="sidebox">
                        <div class="hd">
                            <h2 class="no-toc">Table of Contents</h2>
                        </div>

                        <div class="bd">
                            <ul class="toc">
<li>
<a href="#getting-started">Getting Started</a>
</li>
<li>
<a href="#using">Using the JSONP Utility</a>
<ul class="toc">
<li>
<a href="#basic">Instantiation and the <code>Y.jsonp</code> method</a>
<ul class="toc">
<li>
<a href="#timing">Sending JSONP requests</a>
</li>
</ul>
</li>
<li>
<a href="#config">Configuring the connection</a>
</li>
<li>
<a href="#url">Parsing the callback from the URL</a>
</li>
<li>
<a href="#format">Customizing the JSONP URL</a>
</li>
</ul>
</li>
<li>
<a href="#issues">Known Issues</a>
</li>
</ul>
                        </div>
                    </div>
                

                
                    <div class="sidebox">
                        <div class="hd">
                            <h2 class="no-toc">Examples</h2>
                        </div>

                        <div class="bd">
                            <ul class="examples">
                                
                                    
                                        <li data-description="Get basic GitHub user info using a Y.jsonp(url, callback).">
                                            <a href="jsonp-github.html">Getting Cross Domain JSON Data Using Y.jsonp()</a>
                                        </li>
                                    
                                
                                    
                                        <li data-description="Create a reusable JSONPRequest object to poll the YUILibrary.com Gallery web service, fetching info on a random Gallery module.">
                                            <a href="jsonp-gallery.html">Reusing a JSONPRequest Instance to Poll a Remote Server</a>
                                        </li>
                                    
                                
                                    
                                
                                    
                                
                            </ul>
                        </div>
                    </div>
                

                
                    <div class="sidebox">
                        <div class="hd">
                            <h2 class="no-toc">Examples That Use This Component</h2>
                        </div>

                        <div class="bd">
                            <ul class="examples">
                                
                                    
                                
                                    
                                
                                    
                                        <li data-description="Wrapping async transactions with promises">
                                            <a href="../promise/basic-example.html">Wrapping async transactions with promises</a>
                                        </li>
                                    
                                
                                    
                                        <li data-description="Extend Y.Promise to create classes that encapsulate standard transaction logic in descriptive method names">
                                            <a href="../promise/subclass-example.html">Subclassing Y.Promise</a>
                                        </li>
                                    
                                
                            </ul>
                        </div>
                    </div>
                
            </div>
        </div>
    </div>
</div>

<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>

<script>
YUI.Env.Tests = {
    examples: [],
    project: '../assets',
    assets: '../assets/jsonp',
    name: 'jsonp',
    title: 'JSONP',
    newWindow: '',
    auto:  false 
};
YUI.Env.Tests.examples.push('jsonp-github');
YUI.Env.Tests.examples.push('jsonp-gallery');
YUI.Env.Tests.examples.push('basic-example');
YUI.Env.Tests.examples.push('subclass-example');

</script>
<script src="../assets/yui/test-runner.js"></script>



</body>
</html>