Home > Article > Web Front-end > Perfect solution to AJAX cross-domain issues_javascript skills
Since the day AJAX was born, the problem that XMLHttprequest objects cannot be requested across domains has always existed. This seems to be a very classic question. It is caused by the same origin policy of JavaScript (not discussed in depth here).
The solutions are probably as follows:
1. Use the middle layer transition method (can be understood as "agent"):
Intermediate transition, obviously, is to add a layer of transition in the middle of AJAX communication with servers in different domains. This layer of transition can be any language with network communication functions such as PHP, JSP, C, etc., from the middle layer to Servers in different domains perform data reading operations. Take asp.net as an example. If you need to communicate with an asp.net in different domains, the client's xmlhttprequest first queries an asp.net in this domain, and then the asp.net in this domain communicates with the asp.net in different domains. .net for communication, and then the asp.net response output (response) of this domain; the idea is probably like this, I believe readers have a clear understanding.
2. Use the <script> tag </script>
This method is to use the src in the <script> tag to query an aspx to obtain the response, because the src attribute of the <script> tag does not have cross-domain issues. </script>
Let’s give an example to make it clearer:
远程服务器端js.txt中的内容为:
var Dylan= {name:"Dylan",email:Dylan@163.com}
笔者感觉这种方式更加简洁。呵呵。当然,读者可以根据实际情况,任意选择实现方式。
怎么样,其实很简单吧,我看到过很多人不愿意去正视ajax所存在的技术瓶颈,其实AJAX更应该是Ajax而不是AJAX,突出第一个A是想强调其实AJAX发扬的是一种异步传输的方法,而不是具体到底使用了哪种技术。
其实,在json数据格式之后,有一种更牛X的“jsonp”,也可以实现ajax的跨域通信。其实jsonp不是一种数据格式,只是对我介绍的第二种方式做了改进。从jQuery1.2 版本开始,jQuery 拥有对 JSONP 回调的本地支持。