Ajax Cross-domain and Jsonp (the feature that automatically adds a short address for the article) _jquery

Source: Internet
Author: User
Tags script tag
What is a Cross-domain request for Ajax
For security reasons, if you want to request another website www.b.com from Www.a.com via Ajax, browsers are not allowed to do this (what does it mean to be safe here?). Think about what a hacker can do without that limitation. So what kind of situation is a cross domain? Domain name different that certainly is cross-domain, for example a.com send a request to B.Com, this is certainly cross-domain, not allowed. However, different subdomains (such as sub.a.com sending requests to www.a.com) and even different ports (such as a.com:80 to a.com:8080) are cross-domain.
A cross-domain example is shown below:
Copy Code code as follows:

<script type= "Text/javascript" >
jquery Code
$ ("#btnCrossDomainRequest"). Click (function () {
$.get (' Http://www.jb51.net ', function (data) {
Alert (' success ');
});
});
</script>

(IE8 under the hint without permission, in FF3.5.5 and Google browser are not prompted, Khan ~ I remember the previous version of FF is a hint. IE6 should be able to play the window tips (remember correctly))
Solutions for cross-domain AJAX requests
In an AJAX application environment, browsers do not allow XMLHttpRequest components to request Cross-domain resources for security reasons. In many cases, this limitation brings me a lot of inconvenience. Many peers have studied a variety of solutions:
1. Cross-domain requests are implemented by modifying Document.domain and hidden iframe. This scenario may be the simplest one for cross-domain requests, but it is also one of the most restrictive scenarios. First, it can only implement Cross-domain requests under the same top-level domain name and, in addition, may create security exceptions and deny access when there are other iframe in one page.
2. By requesting a proxy for the current domain, the server Agent accesses the resources of another domain. XMLHttpRequest by requesting a server resource in this domain, the target resource to be accessed is provided to the server and the server is delegated access to the target resource. This scenario enables full Cross-domain access, but the development of the request process consumes a lot more.
3. In HTML, you can request a cross domain resource label reference to achieve the goal, such as image,script,link these tags. Of these tags, script is certainly the most appropriate. When requesting each script resource, the browser parses and runs the functions defined within the script file, or the JavaScript code that needs to be executed immediately, and we can return a script or JSON object from the server and parse the execution in the browser to achieve the goal of Cross-domain request. Using the script tag to implement Cross-domain requests, you can only request server resources using the Get method.

The first solution requires that the root domain name be the same, such as a.domain.com and b.domain.com. The entire solution is probably shown in the following illustration:

The second solution is to request Cross-domain content on the server side through WebClient (or other) classes, and here's the point to note that if you want to include cookies in the WebClient request, You need to manually add cookies to the WebClient.

The third solution is related to the JSONP we need to address below.

JSONP
The JSONP full name should be "JSON with padding", which leverages the <script/> features that can be requested across domains. In short, JSONP is the function name that the client will use to process the result of the request as a parameter to the server side, while the server side wraps the request result data as a parameter in the function and returns it to the client for execution. A little abstract? Then look directly at the picture:

Here is an example to explain. This example is for our blog automatically generated 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.
Copy Code code 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 Test, what? No? Definitely not, because it's a cross-domain, so we need to take advantage of the <script/> tag to request features across domains:
Copy Code code 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;
Notice that the function name ' Alertshorturl ' is passed in here.
C_url = ' &jsonp=alertshorturl '
Generates a <script/> tag and adds it to the Script = $ (' <script type= "text/javascript"/> ')
. attr (' src ', c_url);
Why do you use appendchild here?
Because the Append method of jquery has handled <script/>
You can also use $ (' head '). Append (script);
It's not just to make you see more clearly.
$ (' head ') [0].appendchild (Script[0]);
});
</script>


Haha, a little bit more Test button to see? Good, it's done.
It doesn't have to be such a hassle, because jquery has added support for JSONP since version 1.2, and you just need to give a question mark as a placeholder, so our code above can be written as:
Copy Code code 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 there is only a question mark, not a specific function name
C_url = ' &jsonp=? '
Look, it's getjson.
$.getjson (C_url, function (data) {
alert (data);
});
});
</script>

Haha, isn't it easy? The following is to use this implementation for our article to add the function of automatically shortened URL:
Copy Code code 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 there is only a question mark, not a specific function name
C_url = ' &jsonp=? '
$.getjson (C_url, function (data) {
This is the way to deal with, where to put to see you like it. And it's related to the template you use for your blog.
$ ("<div> This article short address:</div>"). CSS ("font-weight", "normal")
. CSS ("Font-size", "12px")
. Append ($ ("<a>" +data+ "</a>"). attr ("href", data)
. Appendto (". Post. Posttitle");
});
});
</script>

OK, finish the call. Enjoy it!
Say a few more, on Twitter many still use bit.ly, J.mp and so on foreign short address service, the wall is formidable, every time can not see very depressed. Try not to use those walls badly.
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.