JSONP learning (collected)

What is the connection between you and JSONP JSON?

The JSON (the JavaScript Object Notation) is a lightweight, readable text-based data interchange format. , It is a lightweight open standard data exchange. From JavsScript programming language display function for simple data structures and associative arrays. It contains only transfer data and plain text in parentheses simple structure, it can be many ways of JSON messages. For JSON we should be very understanding of it, is not very clear friends can go json.org under the understanding.

1. JSONP defined
    JSONP JSON with Padding is the English abbreviation, it is an unofficial agreement. It allows you to generate script tags returned to the client to achieve the form of javascript callback on the server side
cross-domain access (this is just a simple realization JSONP form) - the source of Baidu . JSONP is a script tag injection, add the server returns the response to the page for specific functions.

2.JSONP Origin

    JSONP to explain the reason, first talk about the browser's "Same Origin Policy (SOP: Same Origin Policy)". In short, the browser can only limit the script and the same protocol, the same domain name, to interact with the script ports, including sharing and transfer variables. The transfer is subject to the same cookie policy. This has resulted in some applications involving multiple servers in the integration of some trouble. A cross-domain access problems caused by the site of Ajax code can not access the data B site.

     How to solve cross-domain access it? We must rely on the browser a feature's: Although browsers do not allow cross-domain script pages to read data, but allow HTML reference to cross-domain resources, such as images, CSS and scripts. A reference to the special script, after it has been parsed by the browser and on the local script indistinguishable and can be interpreted and executed immediately. As a js file B site, a simple prompt box: alert ( "This is Victor! ") ;. A reference in this js site, the script will be executed in the application of B site, display an alert message. Since the outer-site scripting reference is achieved through script tag, while the script but also can be controlled (including dynamically create script tag) tags for all HTML pages by way of DOM, which can be invoked outside the station program a change of local resources. Further, by the <script> tag is used, can be returned directly executable from the server or JSON JavaScript function call data.

 3. JSONP principle --CallBack
    first client to register a callback, then the callback name to the server. At this point, Mr. servers into JSON data. Then by way of JavaScript syntax, to generate a function, parameter function name is passed up jsonp.

    Then, the data directly into the reference JSON manner, placed in function, thus generating a js document grammar, back to the client.
    Finally, resolve in the client browser script tags, JavaScript and execute documents returned, this time as the data parameter passed to the client pre-defined callback function (dynamic callback function).

JSONP is actually a very simple thing. Mainly using the <script /> tag for the dynamic analysis of the document javascript to achieve. (In fact, you can also use the eval function) 

 JSONP implementation code:

// remote server js file code: 
localHandler ({ "the Result": "I was brought js remote data" }); 

// HTML page code under local server: 
! <DOCTYPE HTML the PUBLIC "- // the W3C // DTD 1.0 Transitional // EN XHTML "" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> 
<HTML xmlns =" the http://www.w3.org/1999/xhtml " > 
<head> 
    <title> </ title> 
    <Script type = "text / JavaScript"> var localHandler = function (Data) { 
        Alert ( 'I am local functions, can be called cross-domain remote.js files, remote js data is brought: '+ data.result); 
    }; </ Script> 
    <Script type = "text / JavaScript" the src = "http://remoteserver.com/remote.js"></script>
</head>
<body>
</body>
    
    
</html>

After running View Results, page successfully prompted window, displays the local function is a cross-domain remote js call succeeds, and also received the data from a remote js brings. Very pleased, the purpose of cross-domain remote access to data basically achieved, but it is a problem, how do I let the remote js function it should call the local know What is the name of it? After all, the service is jsonp who have to face a lot of clients, and these serve their local functions are not the same ah?

This is actually a simple implementation JSONP mode, or is JSONP prototype: create a callback function (localHandler) , then call this function on the remote service and the JSON data format passed as parameters to complete the correction .

The JSON data into the filling callback function , which is JSONP of JSON + Padding meaning of it.

The above example is the simplest JSONP implementation model, but it is not really a real JSONP service. Let's look at the real JSONP service is kind of how, such as Google's search interface ajax: http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=?&callback=? 

  • q =? This is a question mark what you want to search, the most important is the second callback =? This is, as its name indicates the name of the callback function, that is, the transfer function name of your own callback functions defined in the client to the server, the server will be returned to the callback function name of your method definition, the acquired data into the json completion callback method.

Local server html page code to read:

<! DOCTYPE HTML> 
<HTML> 
<head> 
    <title> </ title> 
    <Script type = "text / JavaScript"> // callback function after the flight information obtained result var flightHandler = function (Data) { 
        Alert ( ' These are the results of your query: fares' + data.price + 'yuan' + 'than votes' + data.tickets +' sheets' ); 
    }; // provide services jsonp url address (no matter what type address, return values are finally generated javascript code section) var URL = "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998&callback=flightHandler" ;
     // create a script tag, set its properties var script document.createElement = ( 'Script' ); 
    Script.setAttribute('src', url);
    
    
    
    
    
    // the script tag is added head, called at this point starts 
    document.getElementsByTagName ( 'head') [0 ] .appendChild (script);
     </ script> 
</ head> 
<body> 
</ body> 
</ HTML>

Server-side js

flightHandler({
    "code": "CA1998",
    "price": 1780,
    "tickets": 5
});

4. jQuery achieve the JSONP

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" >
 <head>
     <title>Untitled Page</title>
      <script type="text/javascript" src=jquery.min.js"></script>
      <script type="text/javascript">
     jQuery(document).ready(function(){
        $.ajax({
             type: "get",
             async: false,
             url: "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998",
             dataType: "jsonp",
             jsonp: "callback", // passed to the request handler or page to get the parameter name jsonp callback function name (usually the default is: callback) 
             jsonpCallback: "flightHandler", // jsonp callback custom name, the default is automatically generated random jQuery function name, you can also write, jQuery will automatically process the data for you "?" 
             Success: function (json) { 
                 Alert ( 'queries to your flight information: Tickets:' + json.price + ' yuan, ticket I:. '+ json.tickets +' sheets' ); 
             }, 
             error: function () { 
                 Alert ( 'Fail' ); 
             } 
         }); 
     });
      </ Script> 
     </ head> 
  <body> 
  </body>
 </html>

Is not it strange? Why this time did not write flightHandler this function? And surprisingly successful operation! Haha, this is a credit to the jQuery, jquery when dealing jsonp type of ajax, automatic callback and help you generate the data taken out for success attributes method to invoke

5. JSONP Java servlet implementation services

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
  throws ServletException, IOException {
    String jsonData = getDataAsJson(req.getParameter("symbol"));
    String output = req.getParameter("callback") + "(" + jsonData + ");";
    resp.setContentType("text/javascript");          
    PrintWriter out = resp.getWriter();
    out.println(output);
    // prints: jsonp1232617941775({"symbol" : "IBM", "price" : "91.42"});
}

6. ready-made JSONP service

Know how to use JSONP After that, you can start using some ready-made JSONP Web services to build applications and mashup. Here in preparation for the next development project.

  • Digg API: headlines from Digg's: http://services.digg.com/stories/top?appkey=http%3A%2F%2Fmashup.com&type=javascript&callback=?
  • Geonames API: Postcode location: http://www.geonames.org/postalCodeLookupJSON?postalcode=10504&country=US&callback=?
  • Flickr API: The latest from Flickr cat picture: http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?
  • Yahoo Local Search API: zip code is 10504 in the search area Pisa: http://local.yahooapis.com/LocalSearchService/V3/localSearch?appid=YahooDemo&query=pizza&zip=10504&results=2&output=json&callback=?

Description:

  • ajax jsonp and these two technologies is called in the "look" like an object, too, is a request url, then the server returns the data is processed, and therefore jquery ext jsonp like frame regarded as an ajax forms is encapsulated;
  • But in fact, ajax and jsonp something different nature. Ajax is to acquire non-core content on this page by XmlHttpRequest, while the core jsonp is dynamically added <script> tag to call js script server.
  • So, in fact, ajax and jsonp difference is not whether a cross-domain, as ajax proxy server can be achieved through cross-domain, jsonp itself does not get the same exclusive domain data.
  • There is, one way or jsonp is optional protocol, as ajax, like, it does not necessarily have to use json format to transfer data, if you will, the string will do, but this is not conducive provided with jsonp public service.

JSONP defects

    JSONP is a powerful technique to build mashup, but unfortunately, it is not a panacea for all cross-domain communication needs. It has some flaws, it must seriously consider them.

  • First and most importantly, no error handling on JSONP call. If the dynamic script insertion effective implementation calls; If not, fail silently. Failure is without any prompting. For example, from the server 404 can not capture the error can not be canceled or re-start request. But, wait a period of time has not responded, then you do not ignore it. (Future jQuery versions may have termination properties JSONP request).
  • Second, it will be very dangerous when not in use JSONP trust services. Because JSONP service returns JSON response packaged in a function call, and the function call is executed by the browser, which enables the host Web applications are more susceptible to all kinds of attacks. If you plan to use JSONP service, understand the threat it can cause is very important.

reference:

Reproduced in: https: //www.cnblogs.com/JoannaQ/p/3511577.html

Guess you like

Origin blog.csdn.net/weixin_33857679/article/details/93057049