Cross-origin and JSONP of AJAX (the function of automatically adding a short address to an article)

Source: Internet
Author: User

What Is AJAX cross-origin request?
For the sake of security, if you want to request the content of another website www. B .com via Ajax from www.a.com, the browser does not allow you to do this (I do not understand what security here refers? Think about what hackers can do without this restriction ). Under what circumstances is cross-origin? Domain names are different. For example, if a.com sends a request to B .com, this is, of course, cross-domain. This is not allowed. However, different subdomain names (for example, sub.a.com sends requests to www.a.com) or even different ports of the same domain name (for example, a.com: 80 sends requests to a.com: 8080) are also cross-domain.
The following is an example of cross-origin: Copy codeThe Code is as follows: <script type = "text/javascript">
// JQuery code
$ ("# BtnCrossDomainRequest"). click (function (){
$. Get ('HTTP: // www.jb51.net', function (data ){
Alert ('success ');
});
});
</Script>

(The system prompts that you do not have the permission in IE8, and there is no prompt in FF3.5.5 or Google browser, Khan ~ I remember that there was a prompt for FF earlier versions .. In IE6, a pop-up prompt appears (if you remember correctly ))
Cross-origin AJAX request Solution
In the AJAX application environment, the browser does not allow the XMLHttpRequest component to request cross-origin resources for security reasons. In many cases, this restriction causes a lot of inconvenience. Many colleagues have studied various solutions:
1. modify document. domain and the hidden IFrame to implement cross-origin requests. This scheme may be the simplest one for cross-origin requests, but it is also the most restrictive scheme. First, it can only implement cross-origin requests under the same top-level domain name. In addition, when another IFrame is contained in a page, security exceptions may occur and access is denied.
2. By requesting the proxy of the current domain, the server proxy can access resources of another domain. XMLHttpRequest requests a server resource in the domain and provides the target resource to be accessed to the server. The server then acts as a proxy to access the target resource. This scheme can achieve full cross-origin access, but the consumption of the request process will be relatively large during development.
3. You can request cross-origin resource tag reference in HTML, such as Image, Script, and LINK tags. Among these tags, Script is undoubtedly the most suitable. When requesting every script resource, the browser will parse and run the functions defined in the script file, or JavaScript code that needs to be executed immediately. We can return a script or JSON object through the server, execute the parsing in the browser to achieve the purpose of cross-origin requests. Use the script tag to implement cross-origin requests. You can only use the get method to request server resources.

The first solution requires the same root domain name, such as a.domain.com and B .domain.com. The overall solution is as follows:

The second solution is to request cross-origin content through WebClient (or other) classes on the server side. Note that, if you want to include cookies in WebClient requests, You need to manually add Cookies to WebClient.

The third solution is related to the JSONP that we need to talk about below.

JSONP
The full name of JSONP should be "JSON with padding", which utilizes the <script/> Cross-origin request feature. In short, JSONP is the function name that the client will use to process the request results as a parameter and pass it to the server, however, the server wraps the request result data in this function as a parameter and returns it to the client for execution. A little abstract? Let's look at the figure directly:

The following is an example. This instance is for our blog automatically generate a short address url, for the convenience of friends in the wall, we directly use the domestic http://s8.hk provided by the short address service (API address ).
Let's try it out.Copy codeThe Code is as follows: <script type = "text/javascript">
$ ("# ShortIt"). click (function (){
C_url = 'HTTP: // s8.hk: 8088/s8/s? Format = text & longUrl = ';
C_url + = document. location. href;
$. Get (c_url, function (data ){
Alert (data );
})
});
</Script>

Under the test, what? No? Certainly not. Because it is cross-origin, we need to use the <script/> tag to provide cross-origin request features:Copy codeThe Code is as follows: <script type = "text/javascript">
Function alertShortUrl (url ){
Alert (url );
}
$ ("# ShortItByJSONP"). click (function (){
C_url = 'HTTP: // s8.hk: 8088/s8/s? Format = text & longUrl = ';
C_url + = document. location. href;
// Note the following: Upload the function name 'alert0000url '.
C_url + = '& jsonp = alertshorturl'
// Generate a <script/> label and add it to Script = $ ('<script type = "text/javascript"/> ')
. Attr ('src', c_url );
// Why is appendChild used here?
// Because the jQuery append method has already processed <script/>
// You can also use $ ('head'). append (script );
// You do not need to make it clearer here.
$ ('Head') [0]. appendChild (script [0]);
});
</Script>

Haha, click the test button again? Good. It's successful.
In fact, you don't need to worry about this because jQuery has added support for JSONP since version 1.2. You only need to give a question mark as a placeholder, so the above Code can be written:Copy codeThe Code is as follows: <script type = "text/javascript">
$ ("# ShortItByjQueryJSONP"). click (function (){
C_url = 'HTTP: // s8.hk: 8088/s8/s? Format = text & longUrl = ';
C_url + = document. location. href;
// Note that only one question mark is required and no specific function name is required.
C_url + = '& jsonp =? '
// Note getJSON.
$. GetJSON (c_url, function (data ){
Alert (data );
});
});
</Script>

Haha, isn't it easy? Next we will use this function to add the function of automatically shortening the URL for our article:Copy codeThe Code is as follows: <script type = "text/javascript">
$ (Function (){
C_url = 'HTTP: // s8.hk: 8088/s8/s? Format = text & longUrl = ';
C_url + = document. location. href;
// Note that only one question mark is required and no specific function name is required.
C_url + = '& jsonp =? '
$. GetJSON (c_url, function (data ){
// If you want to do this here and put it wherever you like it, it depends on the template used by your blog.
$ ("<Div> short address of this article: </div>" developer.css ("font-weight", "normal ")
. Css ("font-size", "12px ")
. Append ($ ("<a>" + data + "</a>"). attr ("href", data ))
. AppendTo (". post. postTitle ");
});
});
</Script>

OK. Enjoy it!
A few more words, many twitter still use bit. ly, j. mp and other overseas short site services, the wall is so powerful that every time I don't see it very depressing. Try not to use those walls.

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.