In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "JSONP how to solve the ajax cross-domain problem", the content is easy to understand, clear, hope to help you solve the doubt, the following let the editor lead you to study and learn "JSONP how to solve the ajax cross-domain problem" this article.
JSON and JSONP
JSONP and JSON seem to be. Is there any connection between them?
JSON (JavaScript Object Notation) is a lightweight data exchange format. For JSON we should be very familiar with it, not very clear friends can go to json.org to understand, simple and easy to understand.
JSONP is the abbreviation of JSON with Padding. It is an unofficial protocol that allows integration of Script tags on the server side to return to the client and cross-domain access in the form of javascript callback (this is only a simple implementation of JSONP).
JSONP is like JSON+Padding (Padding here we understand as padding), let's take a look at the following small example and then describe it in more detail.
Homologous strategy
Why did you make such a mistake? This is because all browsers that support Javascript use the same origin policy as a security policy. Take a look at Baidu's explanation:
Homologous policy, which is a famous security policy proposed by Netscape. All browsers that support JavaScript now use this strategy. The so-called homology means that the domain name, protocol and port are the same. When a browser opens two tab pages of Baidu and Google respectively, when a Baidu browser executes a script, it will check which page the script belongs to, that is, check whether it is of the same origin. Only scripts of the same origin with Baidu will be executed.
That's why you can't get the data, so how can you solve the cross-domain problem? Yes, we can now get down to business and find out what JSONP is.
The simple principle of cross-domain
Just looking at the definition is not very clear, so first of all, let's do a simple and easy-to-understand test by hand. Create a new web program for asp.net, add a sample.html web page and a test.js file, as follows:
The code for sample.html:
Test
The code for test.js:
Alert ("success")
When you open sample.html, you will pop up an information box like "success", which doesn't seem to mean anything. How to solve the cross-domain problem? OK, now let's simulate a non-homologous environment. We have just created a new Web program with Visual Studio (here we call it Program A). Now we open a new Visual Studio and create a new Web program (Program B). Remove our previous test.js file from Program An and copy it into Program B. After both programs are running, Visual Studio starts the built-in server, assuming that A program is localhost:20001,B program is localhost:20002, which simulates a non-homologous environment (although the domain name is the same but the port number is different, so it is non-homologous).
OK, we should change the code in sample.html next, because when the test.js file is on the B program, url becomes localhost:20002.
Part of the sample.html code:
Please keep the two Web programs of AB running. When you refresh localhost:20001/sample.html again, you will jump out of the "success" dialog box as before. Yes, you have successfully accessed the so-called remote service of non-homologous localhost:20002/test.js. At this point, I believe you should have a general understanding of the principle of cross-domain access.
The src attribute of the tag is not bound by the same origin policy, so you can get the script on any server and execute it.
The implementation Mode of JSONP-- CallBack
The little example just explained the principle of cross-domain. Let's go back and take a look at the form of javascript callback in the definition specification of JSONP. So let's modify the code to see how to implement the javascript callback form of JSONP.
Part of the code of sample in program A:
/ / callback function function callback (data) {alert (data.message);}
The code of test.js in program B:
/ / call the callback function and pass it in the form of json data to complete the callback
Callback ({message: "success"})
This is actually the simple implementation pattern of JSONP, or the prototype of JSONP: create a callback function, then call this function on the remote service and pass the JSON data form as an argument to complete the callback.
Populate the JSON data into the callback function, which is what JSONP's JSON+Padding means.
In general, we want this script tag to be called dynamically, rather than being executed without waiting for the page to be displayed because it is fixed in the html above. We can create script tags dynamically through javascript, so we have the flexibility to invoke remote services.
Part of the code of sample in program A:
Function callback (data) {alert (data.message);} / / method for tagging function addScriptTag (src) {var script = document.createElement ('script'); script.setAttribute ("type", "text/javascript"); script.src = src; document.body.appendChild (script);} _ window.onload = function () {addScriptTag ("http://localhost:/test.js");})
The test.js code of program B remains the same, let's execute the program again, is it the same as the original? If we want to invoke a remote service again, just add the addScriptTag method and pass in the SRC value of the remote service. Here we explain why we put the addScriptTag method into the _ window.onload method. The reason is that there is a sentence document.body.appendChild (script) in the addScriptTag method. The script tag is added to the body. Since the javascript code we wrote is in the head tag, the document.body has not been initialized yet, so we have to initialize the page first with the _ window.onload method, so there will be no errors.
The above example is the simplest implementation model for JSONP, but it's not really a JSONP service yet. Let's take a look at what real JSONP services look like, such as Google's ajax search interface: http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=?&callback=?
QQ? This question mark indicates what you are searching for, and the most important thing is the second callback=? This is just as its name indicates the name of the callback function, that is, the function name of the callback function defined by yourself on the client side is passed to the server, and the server will return the method with the callback function name you defined, passing the acquired json data into this method to complete the callback. It's a little wordy, so let's take a look at the implementation code:
/ / method for tagging function addScriptTag (src) {var script = document.createElement ('script'); script.setAttribute ("type", "text/javascript"); script.src = src; document.body.appendChild (script) } _ window.onload = function () {/ / search apple, pass the custom callback function name result into the callback parameter addScriptTag ("http://ajax.googleapis.com/ajax/services/search/web?v=.&q=apple&callback=result");") } / / Custom callback function result function result (data) {/ / Let's simply get the url data alert (data.responseData.results [] .unescapedUrl) in the first record of apple search results;}
There are many other JSONP services like this (the following information comes from using JSONP for cross-domain communication, part 1: quickly building a powerful mashup with JSONP and jQuery):
Digg API: headlines from Digg:
Http://services.digg.com/stories/top?appkey=http%3A%2F%2Fmashup.com&type=javascript&callback=?
Geonames API: location information of the zip code:
Http://www.geonames.org/postalCodeLookupJSON?postalcode=10504&country=US&callback=?
Flickr JSONP API: load pictures of the latest cats:
Http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?
Yahoo Local Search API: search for pizza in an area with zip code 10504:
Http://local.yahooapis.com/LocalSearchService/V3/localSearch?appid=YahooDemo&query=pizza&zip=10504&results=2&output=json&callback=?
Next, let's create a simple remote service and implement the same JSONP service as above. Still use Web program An and program B to do the demonstration, this time we create a MyService.ashx file on program B.
The MyService.ashx code of program B:
Public class MyService: IHttpHandler {public void ProcessRequest (HttpContext context) {/ / get callback function name string callback = context.Request.QueryString ["callback"]; / / json data string json = "{\" name\ ":\" chopper\ ",\" sex\ ":\" man\ "}"; context.Response.ContentType = "application/json" / / output: callback function name (json data) context.Response.Write (callback + "(" + json + ")");} public bool IsReusable {get {return false;}}
The call in the sample code of program A:
Function addScriptTag (src) {var script = document.createElement ('script'); script.setAttribute ("type", "text/javascript"); script.src = src; document.body.appendChild (script);} _ window.onload = function () {/ / invoke remote service addScriptTag ("http://localhost:/MyService.ashx?callback=person");") The callback function person function person (data) {alert (data.name + "is a" + data.sex);}
This completes a basic JSONP service call, isn't it easy? let's take a look at how JQuery invokes JSONP.
Implementation of JSONP by jQuery
The jQuery framework also supports JSONP, of course, using the $.getJSON (url, [data], [callback]) method (see http://api.jquery.com/jQuery.getJSON/) for details. Let's modify the code of program An and use the getJSON method of jQuery to implement it (the following example does not use passing parameters to the service, so we only write getJSON (url, [callback]):
$.getJSON ("http://localhost:20002/MyService.ashx?callback=?",function(data){ alert (data.name +" is an a "+ data.sex);})
The result is the same. Note that a callback parameter must be added after url, so that the getJSON method will know that the service is accessed by JSONP, and the question mark after callback is a callback function name that is automatically generated internally. You can debug this function name, such as jQuery17207481773362960666_1332575486681.
Of course, what if we add that we want to specify our own callback function name, or that the service has a fixed callback function name? We can use the $.ajax method to do this (there are many parameters, please refer to http://api.jquery.com/jQuery.ajax) for details. Let's take a look at how to do it:
$.ajax ({url: "http://localhost:20002/MyService.ashx?callback=?", dataType:" jsonp ", jsonpCallback:" person ", success:function (data) {alert (data.name +" is an a "+ data.sex);}})
Yes, jsonpCallback can specify our own callback method name person, and the value of the callback parameter accepted by the remote service is no longer the automatically generated callback name, but person. DataType specifies that remote services are accessed in a JSOPN manner.
The above is all the content of the article "how to solve the cross-domain problem of ajax by JSONP". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.