Web front-end learning process--cross-domain problem

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.