dbo:abstract
|
- JSONP o JSON amb padding és una tècnica de comunicació utilitzada als programes Javascript per realitzar crides des de dominis diferents. JSONP és un mètode concebut per superar la limitació de l'AJAX entre diferents dominis, que únicament permet realitzar peticions a pàgines que es troben sota el mateix domini i port per motius de seguretat. (ca)
- JSONP, or JSON-P (JSON with Padding), is a historical JavaScript technique for requesting data by loading a <script></code> element,<sup id="cite_ref-JSON-P_1-0" class="reference"><a href="#cite_note-JSON-P-1">[1]</a></sup> which is an element intended to load ordinary JavaScript. It was proposed by Bob Ippolito in 2005.<sup id="cite_ref-2" class="reference"><a href="#cite_note-2">[2]</a></sup> JSONP enables sharing of data bypassing same-origin policy, which disallows running JavaScript code to read media DOM elements or XMLHttpRequest data fetched from outside the page's originating site. The originating site is indicated by a combination of URI scheme, host name, and port number.</p><p>JSONP is vulnerable to the data source replacing the innocuous function call with malicious code, which is why it has been superseded by cross-origin resource sharing (available since 2009<sup id="cite_ref-caniuse-cors_3-0" class="reference"><a href="#cite_note-caniuse-cors-3">[3]</a></sup>) in modern applications.</p><div id="toc" class="toc" role="navigation" aria-labelledby="mw-toc-heading"><input type="checkbox" role="button" id="toctogglecheckbox" class="toctogglecheckbox" style="display:none" /><div class="toctitle" lang="en" dir="ltr"><h2 id="mw-toc-heading">Contents</h2><span class="toctogglespan"><label class="toctogglelabel" for="toctogglecheckbox"></label></span></div><ul><li class="toclevel-1 tocsection-1"><a href="#Functionality"><span class="tocnumber">1</span> <span class="toctext">Functionality</span></a></li><li class="toclevel-1 tocsection-2"><a href="#Script_element_injection"><span class="tocnumber">2</span> <span class="toctext">Script element injection</span></a></li><li class="toclevel-1 tocsection-3"><a href="#Security_concerns"><span class="tocnumber">3</span> <span class="toctext">Security concerns</span></a><ul><li class="toclevel-2 tocsection-4"><a href="#Untrusted_third-party_code"><span class="tocnumber">3.1</span> <span class="toctext">Untrusted third-party code</span></a></li><li class="toclevel-2 tocsection-5"><a href="#Whitespace_differences"><span class="tocnumber">3.2</span> <span class="toctext">Whitespace differences</span></a></li><li class="toclevel-2 tocsection-6"><a href="#Callback_name_manipulation_and_reflected_file_download_attack"><span class="tocnumber">3.3</span> <span class="toctext">Callback name manipulation and reflected file download attack</span></a></li><li class="toclevel-2 tocsection-7"><a href="#Cross-site_request_forgery"><span class="tocnumber">3.4</span> <span class="toctext">Cross-site request forgery</span></a></li><li class="toclevel-2 tocsection-8"><a href="#Rosetta_Flash"><span class="tocnumber">3.5</span> <span class="toctext">Rosetta Flash</span></a></li></ul></li><li class="toclevel-1 tocsection-9"><a href="#History"><span class="tocnumber">4</span> <span class="toctext">History</span></a></li><li class="toclevel-1 tocsection-10"><a href="#See_also"><span class="tocnumber">5</span> <span class="toctext">See also</span></a></li><li class="toclevel-1 tocsection-11"><a href="#References"><span class="tocnumber">6</span> <span class="toctext">References</span></a></li><li class="toclevel-1 tocsection-12"><a href="#External_links"><span class="tocnumber">7</span> <span class="toctext">External links</span></a></li></ul></div><h2><span class="mw-headline" id="Functionality">Functionality</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=JSONP&action=edit§ion=1" title="Edit section: Functionality">edit</a><span class="mw-editsection-bracket">]</span></span></h2><p>The HTML <code><script></code> element is generally allowed to execute JavaScript code retrieved from foreign origins. Services replying with pure <a href="/wiki/JSON" title="JSON">JSON</a> data, however, were not able to share data from foreign origins before the adoption of CORS (<a href="/wiki/Cross-origin_resource_sharing" title="Cross-origin resource sharing">Cross-origin resource sharing</a>). </p><p>For example, a request to a foreign service <code>http://server.example.com/Users/1234</code> may return a record for a person named Alice in the JSON format. JSON syntax is consistent with JavaScript's object syntax. </p><div class="mw-highlight mw-highlight-lang-json mw-content-ltr mw-highlight-lines" dir="ltr"><pre><span></span><span class="linenos" data-line="1"></span><span class="p">{</span><span class="linenos" data-line="2"></span> <span class="nt">"Name"</span><span class="p">:</span> <span class="s2">"Alice"</span><span class="p">,</span><span class="linenos" data-line="3"></span> <span class="nt">"Id"</span><span class="p">:</span> <span class="mi">1234</span><span class="p">,</span><span class="linenos" data-line="4"></span> <span class="nt">"Rank"</span><span class="p">:</span> <span class="mi">7</span><span class="linenos" data-line="5"></span><span class="p">}</span></pre></div><p>Without support for CORS, an attempt to use the data across domains results in a JavaScript error.</p><div class="mw-highlight mw-highlight-lang-html mw-content-ltr mw-highlight-lines" dir="ltr"><pre><span></span><span class="linenos" data-line="1"></span><span class="p"><</span><span class="nt">script</span> <span class="na">type</span><span class="o">=</span><span class="s">"application/javascript"</span><span class="linenos" data-line="2"></span> <span class="na">src</span><span class="o">=</span><span class="s">"http://server.example.com/Users/1234"</span><span class="p">></span><span class="linenos" data-line="3"></span><span class="p"></</span><span class="nt">script</span><span class="p">></span></pre></div><p>The browser will download the <code><script></code> file, evaluate its contents, misinterpret the raw JSON data as a block, and throw a syntax error. Even if the data were interpreted as a JavaScript object literal, it could not be accessed by JavaScript running in the browser, since without a variable assignment, object literals are inaccessible.</p><p>In the JSONP usage pattern, the URL request pointed to by the <code>src</code> attribute in the <code><script></code> element returns JSON data, with JavaScript code (usually a function call) wrapped around it. This "wrapped payload" is then interpreted by the browser. In this way, a function that is already defined in the JavaScript environment can manipulate the JSON data. A typical JSONP request and response are shown below.</p><p>The function call to parseResponse is the "P" of JSONP—the "padding" or "prefix" around the pure JSON.<sup id="cite_ref-4" class="reference"><a href="#cite_note-4">[4]</a></sup> For JSONP to work, a server must reply with a response that includes the JSONP function. JSONP does not work with JSON-formatted results. The JSONP function invocation that gets sent back, and the payload that the function receives, must be agreed upon by the client and server. By convention, the server providing the JSON data offers the requesting website to name the JSONP function, typically using the name jsonp or <a href="/wiki/Callback_(computer_programming)" title="Callback (computer programming)">callback</a> as the named query-string parameter, in its request to the server: <code><script src="http://server.example.com/Users/1234?callback=parseResponse"></script>. In this example, the received payload would be: parseResponse({"Name": "Alice", "Id": 1234, "Rank": 7}); (en)
- JSONP o JSON-P (JSON con relleno) es una técnica de JavaScript para solicitar datos cargando una etiqueta <script></code>. Fue propuesto por Bob Ippolito en 2005.<sup id="cite_ref-1" class="reference separada"><a href="#cite_note-1"><span class="corchete-llamada">[</span>1<span class="corchete-llamada">]</span></a></sup> JSONP permite compartir datos sin pasar por la <a href="/wiki/Pol%C3%ADtica_del_mismo_origen" title="Política del mismo origen">política del mismo origen</a>, que no permite ejecutar código <a href="/wiki/JavaScript" title="JavaScript">JavaScript</a> para leer elementos del <a href="/wiki/Document_Object_Model" title="Document Object Model">Modelo de Objetos de Documento</a> (DOM) o datos <a href="/wiki/XMLHttpRequest" title="XMLHttpRequest">XMLHttpRequest</a> obtenidos desde fuera del sitio de origen de la página. El sitio de origen se indica mediante una combinación de <a href="/wiki/Identificador_de_recursos_uniforme" title="Identificador de recursos uniforme">esquema URI, nombre de host y número de puerto</a> . </p><div id="toc" class="toc" role="navigation" aria-labelledby="mw-toc-heading"><input type="checkbox" role="button" id="toctogglecheckbox" class="toctogglecheckbox" style="display:none" /><div class="toctitle" lang="es" dir="ltr"><h2 id="mw-toc-heading">Índice</h2><span class="toctogglespan"><label class="toctogglelabel" for="toctogglecheckbox"></label></span></div><ul><li class="toclevel-1 tocsection-1"><a href="#Funcionalidad"><span class="tocnumber">1</span> <span class="toctext">Funcionalidad</span></a></li><li class="toclevel-1 tocsection-2"><a href="#Inyección_de_elementos_de_script"><span class="tocnumber">2</span> <span class="toctext">Inyección de elementos de script</span></a></li><li class="toclevel-1 tocsection-3"><a href="#Preocupaciones_de_seguridad"><span class="tocnumber">3</span> <span class="toctext">Preocupaciones de seguridad</span></a><ul><li class="toclevel-2 tocsection-4"><a href="#Código_de_terceros_no_confiable"><span class="tocnumber">3.1</span> <span class="toctext">Código de terceros no confiable</span></a></li><li class="toclevel-2 tocsection-5"><a href="#Diferencias_de_espacios_en_blanco"><span class="tocnumber">3.2</span> <span class="toctext">Diferencias de espacios en blanco</span></a></li><li class="toclevel-2 tocsection-6"><a href="#Devolución_de_llamada_de_manipulación_de_nombre_y_ataque_de_descarga_de_archivo_reflejado"><span class="tocnumber">3.3</span> <span class="toctext">Devolución de llamada de manipulación de nombre y ataque de descarga de archivo reflejado</span></a></li><li class="toclevel-2 tocsection-7"><a href="#Cross-site_request_forgery"><span class="tocnumber">3.4</span> <span class="toctext">Cross-site request forgery</span></a></li><li class="toclevel-2 tocsection-8"><a href="#Rosetta_Flash"><span class="tocnumber">3.5</span> <span class="toctext">Rosetta Flash</span></a></li></ul></li><li class="toclevel-1 tocsection-9"><a href="#Historia"><span class="tocnumber">4</span> <span class="toctext">Historia</span></a></li><li class="toclevel-1 tocsection-10"><a href="#Véase_también"><span class="tocnumber">5</span> <span class="toctext">Véase también</span></a></li><li class="toclevel-1 tocsection-11"><a href="#Referencias"><span class="tocnumber">6</span> <span class="toctext">Referencias</span></a></li><li class="toclevel-1 tocsection-12"><a href="#Enlaces_externos"><span class="tocnumber">7</span> <span class="toctext">Enlaces externos</span></a></li></ul></div><h2><span class="mw-headline" id="Funcionalidad">Funcionalidad</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=JSONP&action=edit§ion=1" title="Editar sección: Funcionalidad">editar</a><span class="mw-editsection-bracket">]</span></span></h2><p>El elemento HTML <code><script></code> generalmente puede ejecutar código JavaScript recuperado de orígenes externos. Sin embargo, los servicios que respondieron con datos <a href="/wiki/JSON" title="JSON">JSON</a> puros no pueden compartir datos de orígenes externos antes de la adopción de CORS (<a href="/wiki/Intercambio_de_recursos_de_origen_cruzado" title="Intercambio de recursos de origen cruzado">intercambio de recursos de origen cruzado</a>). </p><p>Por ejemplo, una solicitud a un servicio externo <code>http://server.example.com/Users/1234</code> puede devolver un registro de una persona llamada Alice en el formato JSON. La sintaxis JSON es coherente con la sintaxis de objetos de JavaScript: </p><div class="mw-highlight mw-highlight-lang-json mw-content-ltr mw-highlight-lines" dir="ltr"><pre><span></span><span class="linenos" data-line="1"></span><span class="p">{</span><span class="w"></span><span class="linenos" data-line="2"></span><span class="w"> </span><span class="nt">"Name"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Alice"</span><span class="p">,</span><span class="w"></span><span class="linenos" data-line="3"></span><span class="w"> </span><span class="nt">"Id"</span><span class="p">:</span><span class="w"> </span><span class="mi">1234</span><span class="p">,</span><span class="w"></span><span class="linenos" data-line="4"></span><span class="w"> </span><span class="nt">"Rank"</span><span class="p">:</span><span class="w"> </span><span class="mi">7</span><span class="w"></span><span class="linenos" data-line="5"></span><span class="p">}</span><span class="w"></span></pre></div><p> Sin soporte para CORS, un intento de usar los datos entre dominios da como resultado un error de JavaScript: </p><div class="mw-highlight mw-highlight-lang-html mw-content-ltr mw-highlight-lines" dir="ltr"><pre><span></span><span class="linenos" data-line="1"></span><span class="p"><</span><span class="nt">script</span> <span class="na">type</span><span class="o">=</span><span class="s">"application/javascript"</span><span class="linenos" data-line="2"></span> <span class="na">src</span><span class="o">=</span><span class="s">"http://server.example.com/Users/1234"</span><span class="p">></span><span class="linenos" data-line="3"></span><span class="p"></</span><span class="nt">script</span><span class="p">></span></pre></div><p> El navegador descargará el archivo apuntado dentro de la etiqueta <code><script></code>, evaluará su contenido, malinterpretará los datos JSON sin procesar como un bloque y arrojará un error de sintaxis. Incluso si los datos se interpretaran como un literal de objeto de JavaScript, JavaScript no podría acceder a él cuando se ejecutara en el navegador, ya que sin una asignación variable, los literales de objeto son inaccesibles. </p><p>En el patrón de uso JSONP, la solicitud de URL señalada por el atributo <code>src</code> en el elemento <code><script></code> devuelve datos JSON, con un código JavaScript (generalmente una llamada a función) envuelto alrededor de él. Esta "<a href="/wiki/Carga_%C3%BAtil_(inform%C3%A1tica)" title="Carga útil (informática)">carga útil</a> envuelta" es interpretada por el navegador. De esta manera, una función que ya está definida en el entorno JavaScript puede manipular los datos JSON. A continuación se muestra una solicitud y respuesta JSONP típica. </p><p>La llamada a la función <code class="mw-highlight mw-highlight-lang-text mw-content-ltr" id="" style="" dir="ltr">parseResponse</code> es la "P" de JSONP: el "relleno" o "prefijo" alrededor del JSON puro.<sup id="cite_ref-2" class="reference separada"><a href="#cite_note-2"><span class="corchete-llamada">[</span>2<span class="corchete-llamada">]</span></a></sup> Para que JSONP funcione, un servidor debe entregar una respuesta que incluya la función JSONP. JSONP no funciona con resultados con formato JSON. El cliente y el servidor deben acordar la invocación de la función JSONP que se devuelve y la carga útil que recibe la función. Por convención, el servidor que proporciona los datos JSON ofrece al sitio web solicitante el nombre de la función JSONP, generalmente utilizando el nombre jsonp o <a href="/wiki/Callback_(inform%C3%A1tica)" class="mw-redirect" title="Callback (informática)">devolución de llamada</a> como parámetro de cadena de consulta con nombre, en su solicitud al servidor: <code><script src="<nowiki><a rel="nofollow" class="external free" href="http://server.example.com/Users/1234?callback=parseResponse">http://server.example.com/Users/1234?callback=parseResponse</a></nowiki>"> </script>. En este ejemplo, la carga útil recibida sería: parseResponse({"Name": "Alice", "Id": 1234, "Rank": 7}); (es)
- JSONP(JSON with Padding 또는 JSON-P)는 클라이언트가 아닌, 각기 다른 도메인에 상주하는 서버로부터 데이터를 요청하기 위해 사용된다. 2005년에 Bob Ippolito가 제안하였다. JSONP는 동일-출처 정책을 우회하는 데이터의 공유를 가능하게 한다. 이 정책은 페이지의 출처 밖에서 가져온 미디어 DOM 요소나 XHR 데이터를 읽기 위해 자바스크립트를 실행하는 것을 허용하지 않는다. 사이트의 스킴, 포트 번호, 호스트 이름의 집합은 출처로 식별된다. 상속 비보안 문제로 인해 JSONP는 CORS로 대체되고 있다. (ko)
- JSONP (JSON with padding) とは、scriptタグを使用してクロスドメインな(異なるドメインに存在する)データを取得する仕組みのことである。HTMLのscriptタグ、JavaScript(関数)、JSONを組み合わせて実現される。 クロスドメインな通信を実現する方法としては、後に (CORS)も開発され、JSON-Pに代わる選択肢となっている。 (ja)
- JSONP ou "JSON with padding" é um complemento ao formato de dados JSON. Ele provê um método para enviar requisições de dados de um servidor para um domínio diferente, uma coisa proibida pelos navegadores típicos por causa da Política de mesma origem. Com a Política de mesma origem, uma página servida de server1.example.com não pode normalmente se conectar ou se comunicar com servidores diferentes de server1.example.com. Uma exceção é a tag HTML <script></code>. Explorando a política aberta para a tag <code><script></code>, algumas páginas usam a tag para receber código <a href="/wiki/JavaScript" title="JavaScript">Javascript</a> que opera com dados em formato JSON de outra origem gerados dinamicamente. Esse padrão de uso é conhecido com JSONP. Requisições de JSONP não trazem JSON, mas código Javascript arbitrário. Eles são executados pelo <a href="/wiki/Interpretador" title="Interpretador">interpretador</a> Javascript, e não parseados pelo parser JSON.</p><p>Tem sido levantadas algumas críticas ao JSONP. <a href="/wiki/Cross-origin_resource_sharing" title="Cross-origin resource sharing">Cross-Origin Resource Sharing</a> é um método mais recente de obter dados de um servidor num domínio diferente, que lida com alguma dessas críticas.</p><meta property="mw:PageProp/toc" /><h2><span class="mw-headline" id="Como_funciona">Como funciona</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=JSONP&veaction=edit§ion=1" class="mw-editsection-visualeditor" title="Editar secção: Como funciona">editar</a><span class="mw-editsection-divider"> | </span><a href="/w/index.php?title=JSONP&action=edit§ion=1" title="Editar secção: Como funciona">editar código-fonte</a><span class="mw-editsection-bracket">]</span></span></h2><p>Para ver como esse pattern funciona, considere uma requisição a uma <a href="/wiki/URL" title="URL">URL</a> que retorna um documento JSON. Um programa Javascript pode fazer a requisição dessa URL por <a href="/wiki/XMLHttpRequest" title="XMLHttpRequest">XMLHttpRequest</a>, por exemplo. Suponha que uma URL é <code>http://server2.example.com/RetrieveUser?UserId=xxx</code>. Suponha que userID de Foo é 1234. Um navegador requerendo a URL <code>http://server2.example.com/RetrieveUser?UserId=1234</code>, passando o userID de Foo, pode receber algo como:</p><div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span></span><span class="p">{</span><span class="s2">"Name"</span><span class="o">:</span> <span class="s2">"Foo"</span><span class="p">,</span> <span class="s2">"Id"</span> <span class="o">:</span> <span class="mf">1234</span><span class="p">,</span> <span class="s2">"Rank"</span><span class="o">:</span> <span class="mf">7</span><span class="p">}</span></pre></div><p>Esses dados em formato JSON podem ser dinamicamente gerados, de acordo com os parâmetros passados na URL.</p><p>Agora imagine especificar uma URL que retorna JSON como um atributo src para um elemento <a href="/wiki/HTML_element#script_tag" class="mw-redirect" title="HTML element"><code><script></code></a>. O problema como isso é que o JSON é interpretado com Javascript, mas ao invés de interpretar o conteúdo como notação literal de um objeto ele seria interpretado como um bloco e descartado como um erro de sintaxe. Mesmo que ele fosse corretamente interpretado como uma notação literal de objeto ele não poderia ser acessado por Javascript já que não estaria atribuído a uma variável.</p><p>No uso do JSONP, o atributo src no elemento <code><script></code> é um JSON gerado dinamicamente, com uma chamada de função o encapsulando. Dessa forma, o recurso retornado continua sendo código Javascript válido, mas por ser um literal de um objeto anônimo encapsulado em uma chamada de função, o ambiente Javascript do navegador por agir nos dados retornados. Ele poderia parecer com isso:</p><div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span></span> <span class="nx">functionCall</span><span class="p">({</span><span class="s2">"Name"</span><span class="o">:</span> <span class="s2">"Foo"</span><span class="p">,</span> <span class="s2">"Id"</span> <span class="o">:</span> <span class="mf">1234</span><span class="p">,</span> <span class="s2">"Rank"</span><span class="o">:</span> <span class="mf">7</span><span class="p">});</span></pre></div><p>A chamada de função é o P do JSONP - o "padding" (espaçamento) em volta do JSON puro, ou de acordo com alguns<sup id="cite_ref-1" class="reference"><a href="#cite_note-1"><span>[</span>1<span>]</span></a></sup> o "prefixo".</p><div class="mw-highlight mw-highlight-lang-html mw-content-ltr" dir="ltr"><pre><span></span> <span class="p"><</span><span class="nt">script</span> <span class="na">type</span><span class="o">=</span><span class="s">"text/javascript"</span> <span class="na">src</span><span class="o">=</span><span class="s">"http://server2.example.com/RetrieveUser?UserId=1234&jsonp=parseResponse"</span><span class="p">></span> <span class="p"></</span><span class="nt">script</span><span class="p">></span></pre></div><p>Neste exemplo, a carga recebida seria:</p><div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span></span> <span class="nx">parseResponse</span><span class="p">({</span><span class="s2">"Name"</span><span class="o">:</span> <span class="s2">"Foo"</span><span class="p">,</span> <span class="s2">"Id"</span> <span class="o">:</span> <span class="mf">1234</span><span class="p">,</span> <span class="s2">"Rank"</span><span class="o">:</span> <span class="mf">7</span><span class="p">});</span></pre></div><h2><span class="mw-headline" id="Padding">Padding</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=JSONP&veaction=edit§ion=2" class="mw-editsection-visualeditor" title="Editar secção: Padding">editar</a><span class="mw-editsection-divider"> | </span><a href="/w/index.php?title=JSONP&action=edit§ion=2" title="Editar secção: Padding">editar código-fonte</a><span class="mw-editsection-bracket">]</span></span></h2><p>Enquanto o padding (prefixo) é <i>tipicamente</i> o nome da função callback que é definida dentro do contexto de execução do navegador, ela pode ser uma atribuição de uma variável, trecho de if , ou qualquer outro trecho de código Javascript.A resposta a uma requisição JSONP (nominalmente, uma requisição seguindo a patter de uso do JSONP) não é JSON e não é parseada como JSON; o payload pode ser qualquer expressão Javascript arbitraria, e não precisa nem mesmo incluir JSON. Mas convencionalmente, é um fragmento Javascript que invoca uma chamada de função em algum dado formatado em JSON.Em outras palavras, o uso típico do JSONP provê acesso cross-domanin a uma API JSON existente, encapsulando o conteúdo JSON em uma chamada de função.</p><h2><span id="Inje.C3.A7.C3.A3o_do_elemento_script"></span><span class="mw-headline" id="Injeção_do_elemento_script"><i>Injeção</i> do elemento script</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=JSONP&veaction=edit§ion=3" class="mw-editsection-visualeditor" title="Editar secção: Injeção do elemento script">editar</a><span class="mw-editsection-divider"> | </span><a href="/w/index.php?title=JSONP&action=edit§ion=3" title="Editar secção: Injeção do elemento script">editar código-fonte</a><span class="mw-editsection-bracket">]</span></span></h2><p>JSONP só faz sentido quando usado com o elemento script. Para cada novo request JSONP, o navegador precisa adicionar um novo elemento <a href="/wiki/HTML_element#script_tag" class="mw-redirect" title="HTML element"><code><script></code></a>, ou reutilizar um já existente. A forma antiga, adicionando um novo elemento script, é feita via manipulação dinâmica do DOM, e é conhecida como <i>injeção de elemento script</i>. O elemento <code><script></code> é injetado no DOM, com a URL do endpoint JSON desejado setado como o valor do atributo "src". Esse <i>injeção de elemento script</i> dinâmica é comumente feita por uma biblioteca Javascript auxiliar. jQuery e outros frameworks tem funções auxiliares; há também opções padrões. <sup id="cite_ref-2" class="reference"><a href="#cite_note-2"><span>[</span>2<span>]</span></a></sup></p><p>A <i>injeção dinâmica</i> do elemento script para uma chamada JSONP seria parecido com isso:</p><div class="mw-highlight mw-highlight-lang-html mw-content-ltr" dir="ltr"><pre><span></span> <span class="p"><</span><span class="nt">script</span> <span class="na">type</span><span class="o">=</span><span class="s">"text/javascript"</span> <span class="na">src</span><span class="o">=</span><span class="s">"http://server2.example.com/RetrieveUser?UserId=1234&jsonp=parseResponse"</span><span class="p">></span> <span class="p"></</span><span class="nt">script</span><span class="p">></span></pre></div><p>Após o elemento ser injetado, o navegador interpreta o elemento, e faz um HTTP GET na URL definida no atributo "src", obtendo o conteúdo. O navegador então interpreta o payload como Javascript. Isso é tipicamente uma invocação de função.</p><p>Dessa forma, o uso do JSONP pode ser dito por <i>permite que páginas do navegador contornem a política de mesma origem via injeção de elemento script.</i></p><p><br /></p><h2><span id="Hist.C3.B3ria"></span><span class="mw-headline" id="História">História</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=JSONP&veaction=edit§ion=4" class="mw-editsection-visualeditor" title="Editar secção: História">editar</a><span class="mw-editsection-divider"> | </span><a href="/w/index.php?title=JSONP&action=edit§ion=4" title="Editar secção: História">editar código-fonte</a><span class="mw-editsection-bracket">]</span></span></h2><p>Em Julho de 2005 George Jempty sugeriu uma forma opcional de atribuir uma variavel ao JSON.<sup id="cite_ref-3" class="reference"><a href="#cite_note-3"><span>[</span>3<span>]</span></a></sup><sup id="cite_ref-4" class="reference"><a href="#cite_note-4"><span>[</span>4<span>]</span></a></sup> A proposta original para o JSONP, onde o padding é uma função callback, parece ter sido feita por Bob Ippolito em Dezembro de 2005<sup id="cite_ref-5" class="reference"><a href="#cite_note-5"><span>[</span>5<span>]</span></a></sup> e agora é usado por muitas aplicações <a href="/wiki/Web_2.0" title="Web 2.0">Web 2.0</a> como o <a href="/wiki/Dojo_Toolkit" title="Dojo Toolkit">Dojo Toolkit</a>, <a href="/wiki/Google_Web_Toolkit" title="Google Web Toolkit">Google Web Toolkit</a>,<sup id="cite_ref-6" class="reference"><a href="#cite_note-6"><span>[</span>6<span>]</span></a></sup> e <a href="/wiki/Web_service" title="Web service">Web services</a>.</p><h2><span class="mw-headline" id="References">References</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=JSONP&veaction=edit§ion=5" class="mw-editsection-visualeditor" title="Editar secção: References">editar</a><span class="mw-editsection-divider"> | </span><a href="/w/index.php?title=JSONP&action=edit§ion=5" title="Editar secção: References">editar código-fonte</a><span class="mw-editsection-bracket">]</span></span></h2><div class="reflist columns references-column-width" style="-moz-column-width: 30em; -webkit-column-width: 30em; column-width: 30em; list-style-type: decimal;"><ol class="references"><li id="cite_note-1"><span class="mw-cite-backlink"><a href="#cite_ref-1">↑</a></span> <span class="reference-text"><cite class="citation web"><a rel="nofollow" class="external text" href="https://web.archive.org/web/20141115070803/http://epimorph-pubx1.appspot.com/help.html">«Experimental RDF result set to JSON translator»</a><span class="reference-accessdate">. Consultado em 20 de fevereiro de 2012</span>. Arquivado do <a rel="nofollow" class="external text" href="http://epimorph-pubx1.appspot.com/help.html">original</a> em 15 de novembro de 2014</cite><span title="ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fpt.wikipedia.org%3AJSONP&rft.btitle=Experimental+RDF+result+set+to+JSON+translator&rft.genre=unknown&rft_id=http%3A%2F%2Fepimorph-pubx1.appspot.com%2Fhelp.html&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook" class="Z3988"><span style="display:none;"> </span></span></span></li><li id="cite_note-2"><span class="mw-cite-backlink"><a href="#cite_ref-2">↑</a></span> <span class="reference-text"><cite class="citation web"><a rel="nofollow" class="external text" href="http://pastebin.com/ADxHdCnB">«example jsonp library on pastebin»</a></cite><span title="ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fpt.wikipedia.org%3AJSONP&rft.btitle=example+jsonp+library+on+pastebin&rft.genre=unknown&rft_id=http%3A%2F%2Fpastebin.com%2FADxHdCnB&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook" class="Z3988"><span style="display:none;"> </span></span></span></li><li id="cite_note-3"><span class="mw-cite-backlink"><a href="#cite_ref-3">↑</a></span> <span class="reference-text"><cite class="citation web"><a rel="nofollow" class="external text" href="http://replay.web.archive.org/20060212113746/http://htmatters.net/htm/1/2005/07/evaling-JSON.cfm">«eval'ing JSON»</a>. 19 de julho de 2005</cite><span title="ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fpt.wikipedia.org%3AJSONP&rft.btitle=eval%27ing+JSON&rft.date=2005-07-19&rft.genre=unknown&rft_id=http%3A%2F%2Freplay.web.archive.org%2F20060212113746%2Fhttp%3A%2F%2Fhtmatters.net%2Fhtm%2F1%2F2005%2F07%2Fevaling-JSON.cfm&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook" class="Z3988"><span style="display:none;"> </span></span></span></li><li id="cite_note-4"><span class="mw-cite-backlink"><a href="#cite_ref-4">↑</a></span> <span class="reference-text"><cite class="citation web"><a rel="nofollow" class="external text" href="http://tech.groups.yahoo.com/group/json/message/82">«json: Message: Re: Comments»</a>. 17 de agosto de 2005</cite><span title="ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fpt.wikipedia.org%3AJSONP&rft.btitle=json%3A+Message%3A+Re%3A+Comments&rft.date=2005-08-17&rft.genre=unknown&rft_id=http%3A%2F%2Ftech.groups.yahoo.com%2Fgroup%2Fjson%2Fmessage%2F82&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook" class="Z3988"><span style="display:none;"> </span></span></span></li><li id="cite_note-5"><span class="mw-cite-backlink"><a href="#cite_ref-5">↑</a></span> <span class="reference-text"><cite class="citation web"><a rel="nofollow" class="external text" href="https://www.webcitation.org/65OHzF7n5?url=http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/">«Remote JSON - JSONP»</a>. <i>from __future__ import *</i>. Bob.pythonmac.org. 5 de dezembro de 2005<span class="reference-accessdate">. Consultado em 8 de setembro de 2008</span>. Arquivado do <a rel="nofollow" class="external text" href="http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/">original</a> em 12 de fevereiro de 2012</cite><span title="ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fpt.wikipedia.org%3AJSONP&rft.atitle=Remote+JSON+-+JSONP&rft.date=2005-12-05&rft.genre=unknown&rft.jtitle=from+__future__+import+%2A&rft_id=http%3A%2F%2Fbob.pythonmac.org%2Farchives%2F2005%2F12%2F05%2Fremote-json-jsonp%2F&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal" class="Z3988"><span style="display:none;"> </span></span></span></li><li id="cite_note-6"><span class="mw-cite-backlink"><a href="#cite_ref-6">↑</a></span> <span class="reference-text"><cite class="citation web"><a rel="nofollow" class="external text" href="https://www.webcitation.org/6Djo88laj?url=http://www.gwtapps.com/?p=42">«GWT Tutorial: How to Read Web Services Client-Side with JSONP»</a>. <i>Google Web Toolkit Applications</i>. 6 de fevereiro de 2008<span class="reference-accessdate">. Consultado em 3 de julho de 2009</span>. Arquivado do <a rel="nofollow" class="external text" href="http://www.gwtapps.com/?p=42">original</a> em 17 de janeiro de 2013</cite><span title="ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fpt.wikipedia.org%3AJSONP&rft.atitle=GWT+Tutorial%3A+How+to+Read+Web+Services+Client-Side+with+JSONP&rft.date=2008-02-06&rft.genre=unknown&rft.jtitle=Google+Web+Toolkit+Applications&rft_id=http%3A%2F%2Fwww.gwtapps.com%2F%3Fp%3D42&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal" class="Z3988"><span style="display:none;"> </span></span></span></li></ol></div><h2><span id="Liga.C3.A7.C3.B5es_externas"></span><span class="mw-headline" id="Ligações_externas">Ligações externas</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=JSONP&veaction=edit§ion=6" class="mw-editsection-visualeditor" title="Editar secção: Ligações externas">editar</a><span class="mw-editsection-divider"> | </span><a href="/w/index.php?title=JSONP&action=edit§ion=6" title="Editar secção: Ligações externas">editar código-fonte</a><span class="mw-editsection-bracket">]</span></span></h2><ul><li>Site official: <a rel="nofollow" class="external free" href="http://www.json-p.org">http://www.json-p.org</a> (em inglês)</li><li><a rel="nofollow" class="external text" href="http://www.vcarrer.com/2010/11/about-jsonp-in-javascript.html">About JSONP in JavaScript</a> (em inglês)</li><li><a rel="nofollow" class="external text" href="https://code.google.com/p/jsonp-java/">jsonp-java wraps any response content into a jsonp callback</a> (em inglês)</li><li><a rel="nofollow" class="external text" href="https://web.archive.org/web/20111227014302/http://cheeso.members.winisp.net/srcview.aspx?dir=js">An implementation of a JSONP utility class</a> (em inglês)</li></ul><!-- NewPP limit reportParsed by mw1441Cached time: 20221216193800Cache expiry: 1814400Reduced expiry: falseComplications: [show‐toc]CPU time usage: 0.369 secondsReal time usage: 1.014 secondsPreprocessor visited node count: 593/1000000Post‐expand include size: 15136/2097152 bytesTemplate argument size: 122/2097152 bytesHighest expansion depth: 12/100Expensive parser function count: 7/500Unstrip recursion depth: 0/20Unstrip post‐expand size: 35045/5000000 bytesLua time usage: 0.303/10.000 secondsLua memory usage: 2569761/52428800 bytesNumber of Wikibase entities loaded: 0/400--><!--Transclusion expansion time report (%,ms,calls,template)100.00% 993.460 1 -total 30.63% 304.280 1 Predefinição:Mais_notas 28.99% 288.002 1 Predefinição:Ambox 5.23% 51.923 1 Predefinição:Reflist 4.03% 40.002 6 Predefinição:Citar_web 1.54% 15.286 4 Predefinição:En 1.32% 13.135 1 Predefinição:()-meta1 1.21% 12.011 1 Predefinição:Língua-meta 0.43% 4.260 1 Predefinição:Argvar 0.17% 1.672 1 Predefinição:Encontre_fontes--><!-- Saved in parser cache with key ptwiki:pcache:idhash:3655591-0!canonical and timestamp 20221216193759 and revision id 64429144. --></div></script> (pt)
- JSONP или «JSON with padding» (JSON с набивкой) — это дополнение к базовому формату JSON. Он предоставляет способ запросить данные с сервера, находящегося в другом домене — операцию, запрещённую в типичных веб-браузерах из-за политики ограничения домена. (ru)
- JSONP (англ. JSON with padding, «JSON з підкладкою») є розширенням JSON, коли ім'я функції зворотного виклику вказується як вхідний аргумент. В основу технології покладено той факт, що політика безпеки браузера дозволяє використовувати тег <script type="text/javascript" src="..."></script> для звернення до сторонніх доменів. Спочатку ідея була запропонована в блозі MacPython в 2005 році , і зараз використовується багатьма Web 2.0 застосунками, такими, як Dojo Toolkit Applications, Google Toolkit Applications, Kendo UI і zanox Web Services. Подальші розширення цього протоколу були запропоновані з урахуванням введення додаткових аргументів, як, наприклад, у JSONPP за підтримки вебсервісів. Без використання технології JSONP (тобто використовуючи просто JSON кодування даних) сервер може повернути тільки дані. Наприклад так: {"paper": "A4", "count": 5} Однак це лише дані та вони не можуть впливати на браузер. Використовуючи JSONP, сторонньому серверу передається в рядку виклику (GET) ім'я callback функції: Тут параметр jsonp містить ім'я callback функції parseResponse. Тепер сторонній сервер example.com може повернути такий код: parseResponse({"paper": "A4", "count": 5}) Тепер код викликає javascript-функцію першого домену. Оскільки JSONP використовує скрипт-теги, виклики відкриті світу. З цієї причини, JSONP може бути недоречними для зберігання конфіденційних даних. Включення скриптових тегів від віддалених сайтів дозволяє їм передати будь-який контент на сайті. Якщо віддалений сайт має вразливості, які дозволяють виконати Javascript ін'єкції, то початковий сайт також може зачеплений ними. (uk)
- JSONP(JSON with Padding)是資料格式JSON的一種“使用模式”,可以讓網頁從別的網域获取資料。另一個解決這個問題的新方法是跨來源資源共享。 由於同源策略,一般來說位於server1.example.com的網頁無法與server2.example.com的伺服器溝通,而HTML的<script></code></a>元素是一個例外。利用<a href="/wiki/HTML%E5%85%83%E7%B4%A0#script_tag" title="HTML元素"><code><script></code></a>元素的這個開放策略,網頁可以得到從其他來源動態產生的JSON資料,而這種使用模式就是所謂的JSONP。用JSONP抓到的資料並不是JSON,而是任意的JavaScript,用JavaScript直譯器執行而不是用JSON解析器解析。</p><div id="toc" class="toc" role="navigation" aria-labelledby="mw-toc-heading"><input type="checkbox" role="button" id="toctogglecheckbox" class="toctogglecheckbox" style="display:none" /><div class="toctitle" lang="zh" dir="ltr"><h2 id="mw-toc-heading">目录</h2><span class="toctogglespan"><label class="toctogglelabel" for="toctogglecheckbox"></label></span></div><ul><li class="toclevel-1 tocsection-1"><a href="#原理"><span class="tocnumber">1</span> <span class="toctext">原理</span></a></li><li class="toclevel-1 tocsection-2"><a href="#填充"><span class="tocnumber">2</span> <span class="toctext">填充</span></a></li><li class="toclevel-1 tocsection-3"><a href="#Script元素“注入”"><span class="tocnumber">3</span> <span class="toctext">Script元素“注入”</span></a></li><li class="toclevel-1 tocsection-4"><a href="#安全問題"><span class="tocnumber">4</span> <span class="toctext">安全問題</span></a></li><li class="toclevel-1 tocsection-5"><a href="#跨站请求伪造"><span class="tocnumber">5</span> <span class="toctext">跨站请求伪造</span></a></li><li class="toclevel-1 tocsection-6"><a href="#歷史"><span class="tocnumber">6</span> <span class="toctext">歷史</span></a></li><li class="toclevel-1 tocsection-7"><a href="#參考文獻"><span class="tocnumber">7</span> <span class="toctext">參考文獻</span></a></li><li class="toclevel-1 tocsection-8"><a href="#外部連結"><span class="tocnumber">8</span> <span class="toctext">外部連結</span></a></li></ul></div><h2><span id=".E5.8E.9F.E7.90.86"></span><span class="mw-headline" id="原理">原理</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=JSONP&action=edit§ion=1" title="编辑章节:原理">编辑</a><span class="mw-editsection-bracket">]</span></span></h2><p>為了理解這種模式的原理,先想像有一個回傳JSON文件的URL,而JavaScript程式可以用<a href="/wiki/XMLHttpRequest" title="XMLHttpRequest">XMLHttpRequest</a>跟這個URL要資料。假設我們的URL是http://server2.example.com/RetrieveUser?UserId=xxx 。假設小明的UserId是1823,且當瀏覽器透過URL傳小明的UserId,也就是抓取http://server2.example.com/RetrieveUser?UserId=1823,得到:</p><div class="mw-highlight mw-highlight-lang-json mw-content-ltr" dir="ltr"><pre><span></span><span class="p">{</span><span class="nt">"Name"</span><span class="p">:</span><span class="w"> </span><span class="s2">"小明"</span><span class="p">,</span><span class="w"> </span><span class="nt">"Id"</span><span class="p">:</span><span class="w"> </span><span class="mi">1823</span><span class="p">,</span><span class="w"> </span><span class="nt">"Rank"</span><span class="p">:</span><span class="w"> </span><span class="mi">7</span><span class="p">}</span><span class="w"></span></pre></div><p>這個JSON資料可能是依據傳過去URL的查詢參數動態產生的。</p><p>這個時候,把<a href="/wiki/HTML%E5%85%83%E7%B4%A0#script_tag" title="HTML元素"><code><script></code></a>元素的src屬性設成一個回傳JSON的URL是可以想像的,這也代表從HTML頁面透過script元素抓取JSON是可能的。</p><p>然而,一份JSON文件並不是一個JavaScript程式。為了讓瀏覽器可以在<a href="/wiki/HTML%E5%85%83%E7%B4%A0#script_tag" title="HTML元素"><code><script></code></a>元素執行,從src裡URL回傳的必須是可執行的JavaScript。在JSONP的使用模式裡,該URL回傳的是由函數呼叫包起來的動態生成JSON,這就是JSONP的“填充(padding)”或是“前輟(prefix)”的由來。</p><p>慣例上瀏覽器提供<a href="/wiki/%E5%9B%9E%E8%AA%BF%E5%87%BD%E6%95%B8" class="mw-redirect" title="回調函數">回調函數</a>的名稱當作送至伺服器的請求中命名查詢參數的一部份,例如:</p><div class="mw-highlight mw-highlight-lang-html mw-content-ltr" dir="ltr"><pre><span></span> <span class="p"><</span><span class="nt">script</span> <span class="na">type</span><span class="o">=</span><span class="s">"text/javascript"</span> <span class="na">src</span><span class="o">=</span><span class="s">"http://server2.example.com/RetrieveUser?UserId=1823&jsonp=parseResponse"</span><span class="p">></span> <span class="p"></</span><span class="nt">script</span><span class="p">></span></pre></div><p>伺服器會在傳給瀏覽器前將JSON数据填充到回调函数(parseResponse)中。瀏覽器得到的回應已不是單純的資料敘述而是一個腳本,这样浏览器就可以调用该函数进行处理。在本例中,瀏覽器得到的是:</p><div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span></span><span class="nx">parseResponse</span><span class="p">({</span><span class="s2">"Name"</span><span class="o">:</span> <span class="s2">"小明"</span><span class="p">,</span> <span class="s2">"Id"</span><span class="o">:</span> <span class="mf">1823</span><span class="p">,</span> <span class="s2">"Rank"</span><span class="o">:</span> <span class="mf">7</span><span class="p">});</span></pre></div><h2><span id=".E5.A1.AB.E5.85.85"></span><span class="mw-headline" id="填充">填充</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=JSONP&action=edit§ion=2" title="编辑章节:填充">编辑</a><span class="mw-editsection-bracket">]</span></span></h2><p>雖然這個填充(前輟)“通常”是瀏覽器執行背景中定義的某個回調函數,它也可以是變數賦值、if敘述或者是其他JavaScript敘述。JSONP要求(也就是使用JSONP模式的請求)的回應不是JSON也不被當作JSON解析——回傳內容可以是任意的運算式,甚至不需要有任何的JSON,不過慣例上填充部份還是會觸發函數调用的一小段JavaScript片段,而這個函數呼叫是作用在JSON格式的資料上的。</p><p>另一種說法—典型的JSONP就是把既有的JSON API用函數呼叫包起來以達到跨域存取的解法。</p><h2><span id="Script.E5.85.83.E7.B4.A0.E2.80.9C.E6.B3.A8.E5.85.A5.E2.80.9D"></span><span class="mw-headline" id="Script元素“注入”">Script元素“注入”</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=JSONP&action=edit§ion=3" title="编辑章节:Script元素“注入”">编辑</a><span class="mw-editsection-bracket">]</span></span></h2><p>為了要啟動一個JSONP呼叫(或者說,使用這個模式),你需要一個script元素。因此,瀏覽器必須為每一個JSONP要求加(或是重用)一個新的、有所需src值的<a href="/wiki/HTML%E5%85%83%E7%B4%A0" title="HTML元素"><code><script></code></a>元素到HTML DOM裡—或者說是「注入」這個元素。瀏覽器執行該元素,抓取src裡的URL,並執行回傳的JavaScript。</p><p>也因為這樣,JSONP被稱作是一種“讓使用者利用script元素注入的方式繞開同源策略”的方法。</p><h2><span id=".E5.AE.89.E5.85.A8.E5.95.8F.E9.A1.8C"></span><span class="mw-headline" id="安全問題">安全問題</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=JSONP&action=edit§ion=4" title="编辑章节:安全問題">编辑</a><span class="mw-editsection-bracket">]</span></span></h2><p>使用遠端網站的script標籤會讓遠端網站得以注入<b>任何</b>的內容至網站裡。如果遠端的網站有JavaScript注入漏洞,原來的網站也會受到影響。</p><p>現在有一個正在進行計畫在定義所謂的<a rel="nofollow" class="external text" href="https://web.archive.org/web/20160304044218/http://www.json-p.org/">JSON-P嚴格安全子集</a>,使瀏覽器可以對MIME類別是“application/json-p”請求做強制處理。如果回應不能被解析為嚴格的JSON-P,瀏覽器可以丟出一個錯誤或忽略整個回應。</p><h2><span id=".E8.B7.A8.E7.AB.99.E8.AF.B7.E6.B1.82.E4.BC.AA.E9.80.A0"></span><span class="mw-headline" id="跨站请求伪造">跨站请求伪造</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=JSONP&action=edit§ion=5" title="编辑章节:跨站请求伪造">编辑</a><span class="mw-editsection-bracket">]</span></span></h2><p>粗略的JSONP部署很容易受到<a href="/wiki/%E8%B7%A8%E7%AB%99%E8%AF%B7%E6%B1%82%E4%BC%AA%E9%80%A0" title="跨站请求伪造">跨站请求伪造</a>(CSRF/XSRF)的攻擊<sup id="cite_ref-1" class="reference"><a href="#cite_note-1">[1]</a></sup>。因為HTML <a href="/wiki/HTML%E5%85%83%E7%B4%A0#script_tag" title="HTML元素"><code><script></code></a>標籤在瀏覽器裡不遵守<a href="/wiki/%E5%90%8C%E6%BA%90%E7%AD%96%E7%95%A5" title="同源策略">同源策略</a>,惡意網頁可以要求並取得屬於其他網站的JSON資料。當使用者正登入那個其他網站時,上述狀況使得該惡意網站得以在惡意網站的環境下操作該JSON資料,可能洩漏使用者的密碼或是其他敏感資料。</p><p>只有在該JSON資料含有不該洩漏給第三方的隱密資料,且伺服器僅靠瀏覽器的同源策略阻擋不正常要求的時候這才會是問題。若伺服器自己決定要求的專有性,並只在要求正常的情況下輸出資料則沒有問題。只靠<a href="/wiki/Cookie" title="Cookie">Cookie</a>並不夠決定要求是合法的,這很容易受到<a href="/wiki/%E8%B7%A8%E7%AB%99%E8%AF%B7%E6%B1%82%E4%BC%AA%E9%80%A0" title="跨站请求伪造">跨站请求伪造</a>攻擊。</p><h2><span id=".E6.AD.B7.E5.8F.B2"></span><span class="mw-headline" id="歷史">歷史</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=JSONP&action=edit§ion=6" title="编辑章节:歷史">编辑</a><span class="mw-editsection-bracket">]</span></span></h2><p>2005年夏天,喬治·詹姆提(George Jempty)建議在JSON前面選擇性的加上變數賦值<sup id="cite_ref-2" class="reference"><a href="#cite_note-2">[2]</a></sup><sup id="cite_ref-3" class="reference"><a href="#cite_note-3">[3]</a></sup>。鮑勃·伊波利托(Bob Ippolito)於2005年12月提出了JSONP最原始的提案,其中填充部份已經是回調函數<sup id="cite_ref-4" class="reference"><a href="#cite_note-4">[4]</a></sup>,而現在已有很多<a href="/wiki/Web_2.0" title="Web 2.0">Web 2.0</a>應用程式使用這份提案,像是<a href="/wiki/Dojo_Toolkit" title="Dojo Toolkit">Dojo Toolkit</a>應用程式、<a href="/wiki/Google_Web_Toolkit" class="mw-redirect" title="Google Web Toolkit">Google Web Toolkit</a>應用程式<sup id="cite_ref-5" class="reference"><a href="#cite_note-5">[5]</a></sup>與<a href="/wiki/Web%E6%9C%8D%E5%8B%99" class="mw-redirect" title="Web服務">Web服務</a>。</p><h2><span id=".E5.8F.83.E8.80.83.E6.96.87.E7.8D.BB"></span><span class="mw-headline" id="參考文獻">參考文獻</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=JSONP&action=edit§ion=7" title="编辑章节:參考文獻">编辑</a><span class="mw-editsection-bracket">]</span></span></h2><div class="reflist columns references-column-count references-column-count-2" style="-moz-column-count: 2; -webkit-column-count: 2; column-count: 2; list-style-type: decimal;"><ol class="references"><li id="cite_note-1"><span class="mw-cite-backlink"><b><a href="#cite_ref-1">^</a></b></span> <span class="reference-text"><cite class="citation web">Grossman, Jeremiah. <a rel="nofollow" class="external text" href="http://jeremiahgrossman.blogspot.com/2006/01/advanced-web-attack-techniques-using.html">Advanced Web Attack Techniques using GMail</a>. 2006-01-27 <span class="reference-accessdate"> [<span class="nowrap">2009-07-03</span>]</span>. (原始内容<a rel="nofollow" class="external text" href="https://www.webcitation.org/6Djo5ri6Y?url=http://jeremiahgrossman.blogspot.com/2006/01/advanced-web-attack-techniques-using.html">存档</a>于2013-01-17) <span style="font-family: sans-serif; cursor: default; color:#555; font-size: 0.8em; bottom: 0.1em; font-weight: bold;" title="连接到英语网页">(英语)</span>.</cite><span title="ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fzh.wikipedia.org%3AJSONP&rft.aufirst=Jeremiah&rft.aulast=Grossman&rft.btitle=Advanced+Web+Attack+Techniques+using+GMail&rft.date=2006-01-27&rft.genre=unknown&rft_id=http%3A%2F%2Fjeremiahgrossman.blogspot.com%2F2006%2F01%2Fadvanced-web-attack-techniques-using.html&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook" class="Z3988"><span style="display:none;"> </span></span></span></li><li id="cite_note-2"><span class="mw-cite-backlink"><b><a href="#cite_ref-2">^</a></b></span> <span class="reference-text"><cite class="citation web"><a rel="nofollow" class="external text" href="https://web.archive.org/web/20060212113746/http://htmatters.net/htm/1/2005/07/evaling-JSON.cfm">eval'ing JSON</a>. 2005-07-19 <span class="reference-accessdate"> [<span class="nowrap">2011-06-27</span>]</span>. (<a rel="nofollow" class="external text" href="http://htmatters.net/htm/1/2005/07/evaling-JSON.cfm">原始内容</a>存档于2006-02-12) <span style="font-family: sans-serif; cursor: default; color:#555; font-size: 0.8em; bottom: 0.1em; font-weight: bold;" title="连接到英语网页">(英语)</span>.</cite><span title="ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fzh.wikipedia.org%3AJSONP&rft.btitle=eval%27ing+JSON&rft.date=2005-07-19&rft.genre=unknown&rft_id=http%3A%2F%2Fhtmatters.net%2Fhtm%2F1%2F2005%2F07%2Fevaling-JSON.cfm&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook" class="Z3988"><span style="display:none;"> </span></span></span></li><li id="cite_note-3"><span class="mw-cite-backlink"><b><a href="#cite_ref-3">^</a></b></span> <span class="reference-text"><cite class="citation web"><a rel="nofollow" class="external text" href="https://web.archive.org/web/20081022182148/http://tech.groups.yahoo.com/group/json/message/82">json : Message: Re: Comments</a>. 2005-08-17 <span class="reference-accessdate"> [<span class="nowrap">2011-06-27</span>]</span>. (<a rel="nofollow" class="external text" href="http://tech.groups.yahoo.com/group/json/message/82">原始内容</a>存档于2008-10-22) <span style="font-family: sans-serif; cursor: default; color:#555; font-size: 0.8em; bottom: 0.1em; font-weight: bold;" title="连接到英语网页">(英语)</span>.</cite><span title="ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fzh.wikipedia.org%3AJSONP&rft.btitle=json+%3A+Message%3A+Re%3A+Comments&rft.date=2005-08-17&rft.genre=unknown&rft_id=http%3A%2F%2Ftech.groups.yahoo.com%2Fgroup%2Fjson%2Fmessage%2F82&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook" class="Z3988"><span style="display:none;"> </span></span></span></li><li id="cite_note-4"><span class="mw-cite-backlink"><b><a href="#cite_ref-4">^</a></b></span> <span class="reference-text"><cite class="citation web"><a rel="nofollow" class="external text" href="https://web.archive.org/web/20091204053053/http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/">Remote JSON - JSONP</a>. from __future__ import *. Bob.pythonmac.org. 2005-12-05 <span class="reference-accessdate"> [<span class="nowrap">2008-09-08</span>]</span>. (<a rel="nofollow" class="external text" href="http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/">原始内容</a>存档于2009-12-04) <span style="font-family: sans-serif; cursor: default; color:#555; font-size: 0.8em; bottom: 0.1em; font-weight: bold;" title="连接到英语网页">(英语)</span>.</cite><span title="ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fzh.wikipedia.org%3AJSONP&rft.atitle=Remote+JSON+-+JSONP&rft.date=2005-12-05&rft.genre=unknown&rft.jtitle=from+__future__+import+%2A&rft_id=http%3A%2F%2Fbob.pythonmac.org%2Farchives%2F2005%2F12%2F05%2Fremote-json-jsonp%2F&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal" class="Z3988"><span style="display:none;"> </span></span></span></li><li id="cite_note-5"><span class="mw-cite-backlink"><b><a href="#cite_ref-5">^</a></b></span> <span class="reference-text"><cite class="citation web"><a rel="nofollow" class="external text" href="https://www.webcitation.org/6Djo88laj?url=http://www.gwtapps.com/?p=42">GWT Tutorial: How to Read Web Services Client-Side with JSONP</a>. Google Web Toolkit Applications. February 6, 2008 <span class="reference-accessdate"> [<span class="nowrap">2009-07-03</span>]</span>. (<a rel="nofollow" class="external text" href="http://www.gwtapps.com/?p=42">原始内容</a>存档于2013-01-17) <span style="font-family: sans-serif; cursor: default; color:#555; font-size: 0.8em; bottom: 0.1em; font-weight: bold;" title="连接到英语网页">(英语)</span>.</cite><span title="ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fzh.wikipedia.org%3AJSONP&rft.atitle=GWT+Tutorial%3A+How+to+Read+Web+Services+Client-Side+with+JSONP&rft.date=2008-02-06&rft.genre=unknown&rft.jtitle=Google+Web+Toolkit+Applications&rft_id=http%3A%2F%2Fwww.gwtapps.com%2F%3Fp%3D42&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal" class="Z3988"><span style="display:none;"> </span></span></span></li></ol></div><h2><span id=".E5.A4.96.E9.83.A8.E9.80.A3.E7.B5.90"></span><span class="mw-headline" id="外部連結">外部連結</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=JSONP&action=edit§ion=8" title="编辑章节:外部連結">编辑</a><span class="mw-editsection-bracket">]</span></span></h2><ul><li><cite class="citation web"><a rel="nofollow" class="external text" href="https://web.archive.org/web/20160304044218/http://www.json-p.org/">JSONP首頁</a>. <span class="reference-accessdate"> [<span class="nowrap">2011-06-27</span>]</span>. (<a rel="nofollow" class="external text" href="http://www.json-p.org/">原始内容</a>存档于2016-03-04) <span style="font-family: sans-serif; cursor: default; color:#555; font-size: 0.8em; bottom: 0.1em; font-weight: bold;" title="连接到英语网页">(英语)</span>.</cite><span title="ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fzh.wikipedia.org%3AJSONP&rft.btitle=JSONP%E9%A6%96%E9%A0%81&rft.genre=unknown&rft_id=http%3A%2F%2Fwww.json-p.org%2F&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook" class="Z3988"><span style="display:none;"> </span></span></li></ul><!-- NewPP limit reportParsed by mw1359Cached time: 20230104191026Cache expiry: 1814400Reduced expiry: falseComplications: [show‐toc]CPU time usage: 0.321 secondsReal time usage: 0.359 secondsPreprocessor visited node count: 582/1000000Post‐expand include size: 210156/2097152 bytesTemplate argument size: 417/2097152 bytesHighest expansion depth: 8/100Expensive parser function count: 4/500Unstrip recursion depth: 0/20Unstrip post‐expand size: 8447/5000000 bytesLua time usage: 0.143/10.000 secondsLua memory usage: 7583680/52428800 bytesNumber of Wikibase entities loaded: 0/400--><!--Transclusion expansion time report (%,ms,calls,template)100.00% 225.047 1 -total 42.94% 96.638 1 Template:NoteTA 32.84% 73.897 1 Template:Reflist 32.44% 72.999 6 Template:Cite_web 14.29% 32.166 1 Template:Infobox_file_format 13.20% 29.705 1 Template:Infobox 1.81% 4.067 1 Template:URL 0.60% 1.361 1 Template:Column-count 0.46% 1.039 2 Template:Nowrap--><!-- Saved in parser cache with key zhwiki:pcache:idhash:1601291-0!canonical!zh and timestamp 20230104191026 and revision id 74996466. --></div></script> (zh)
|