Summary of several methods for implementing cross-origin in js (image ping, JSONP, and CORS) _ javascript skills

Source: Internet
Author: User
I used jQuery. ajax and other methods, but often ignored the implementation behind it. This article is some of the gains after learning about AJAX basics and several cross-origin solutions. Cross-Origin

Although the same-origin policy exists, cross-origin is still very common in js, including document. domain, window. name, image ping, jsonp, and CORS. Here we will briefly summarize ping, jsonp, and CORS memos.

Image ping

Images can be loaded from any URL. Therefore, you can set the src of img to URLs of other domains to implement simple cross-origin. You can use the onload and onerror events to determine whether a response is received.

var img=new Image();img.src='http://www.jb51.net';img.onerror=function(){ alert('error');}img.onload=function(){ alert('success');}

An img object is created here, And the url given is the blog address, which is an error event, so an error is displayed. If you change the URL to an image watermark.

You can only send get requests to ping images across domains and cannot access the response text. You can only listen for responses and track ad clicks.

Jsonp

Jsonp is the json with callback function callback, formerly known as json with padding. The translation is the filling json, and the parameter json.

Because the src of the script can be cross-origin, a callback parameter is added after the URL is sent to the server, and the data returned by the server is used as the callback parameter, because this callback is implemented by ourselves, we can process the received json data.

The simple code is as follows:

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.