Solve the problem of cross-origin ajax

Source: Internet
Author: User

There are many solutions for ajax cross-origin calls. Here I will only talk about two solutions:

 

Suppose s.cnblogs.com is a comment system that only supports javascript calls. News.cnblogs.com is a news system that delegates the comment function to s.cnblogs.com. At this time, news.cnblogs.com may comment on the Code:

Function sendData (data, callback)

{

Var xmlHttp = createXmlHttpRequest ();

XmlHttp. open ('post', 'HTTP: // s.cnblogs.com/postHandler.ashx ');

XmlHttp. onreadystatechange = callback;

XmlHttp. send (data); // data contains the data to be sent.

}

This generation of code has a security reminder in IE6, but in IE7, there is a direct error. Because of cross-origin.

Solution 1: document. domain.

1. Save the senddatacode to a services.htm file. And set document. domain = 'cnblogs. com' in services.htm'

2.place services.htm under the root directory of the s.cnblogs.com website.

3. Add <iframe id = 'ajaxframe 'src = 'HTTP: // s.cnblogs.com/services.htm' width = '0' height = '0'> </iframe>

4. Add

Function sendData (data, callback)

{

AjaxFrame. window. sendData (data, callback );

}

And document. domain = 'cnblogs. com ';

Disadvantages of the solution:

Only cross-subdomain issues can be solved.

 

Solution 2: Dynamic script method.

1. Add the <script id = 'ajaxproxy 'src = ''> </script>

Function sendData (data, callback)

{

Var proxy = document. getElementById ('ajaxproxy ');

Proxy. src = 'HTTP: // s.cnblogs.com/postHandler.ashx? Data = "+ data;

Proxy. onreadystatechange = callback;

}

I personally prefer solution 2, but one problem with the solution is that callback can do too little and cannot receive the received data from postHandler. ashx.

However, I think there is a work und, that is, to directly output js in postHandler. ashx, such as alert ('OK');, but I have tested it several times before it becomes a function. It may be my RP problem.

 

 

 

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.