One, homologous strategy
A page of Ajax can only get the same source of the page (protocol, domain name, port number must be the same) data.
Second, Jsonp method
1. JSON and JSONP
JSON (JavaScript Object Notation) is a lightweight data interchange format
Jsonp is the merchants of JSON with padding. It is an unofficial protocol that allows the server-side integration of script tags back to the client to implement cross-domain access via JavaScript callback
2, solve the principle of cross-domain:
First, the SRC attribute of the,<script> tag is not constrained by the same origin policy, so you can get any script on the server and execute it. Create a callback function (function callback (data)
), and then call this function on the remote service (callback ({message: "Success"})
) and pass the JSON data form as a parameter to complete the callback .
fill in the JSON data into the callback function , which is the meaning of Jsonp's json+padding.
3. jquery realizes Jsonp
You can use the $.getjson (Url,[data],[callback]) method:
<script type= "Text/javascript" src= "Http://code.jquery.com/jquery-latest.js" ></script>
<script type= "Text/javascript" >
$.getjson ("http://localhost:20002/MyService.ashx?callback=", function (data) {//Such Getjson method will know is to use JSONP way to access the service, A function name is automatically generated
Alert (Data.name + "is a A" + data.sex);
});
</script>
If you want to customize the name of a function
<script type= "Text/javascript" src= "Http://code.jquery.com/jquery-latest.js" ></script>
<script type= "Text/javascript" >
$.ajax ({
URL: "http://localhost:20002/MyService.ashx?callback=?",
DataType: "Jsonp",
Jsonpcallback: "Person",//Custom function name
Success:function (data) {
Alert (Data.name + "is a A" + data.sex);
}
});
</script>
Web front-end learning process-cross-domain issues