Home > Article > Web Front-end > Introduction to how Ajax implements cross-domain access
This article mainly introduces the issue of how Ajax implements cross-domain access. It has a certain reference value. Now I share it with you. Friends in need can refer to it.
In actual projects, we It is often encountered that different projects under the same domain name call each other's data through Ajax, so the question arises, how to achieve cross-domain through Ajax?
1.Jsonp
Jsonp solves cross-domain problems relatively easily, and the server does not require any configuration. The specific implementation is as follows:
$.ajax({ type: 'get', url: 'http://xxx.com', data: {}, dataType: 'jsonp', success: function (data) { }, error: function (data) { mask.close(); toast('请求失败'); } });
2.CORS
CORS solution requires the front-end and server to be configured together to achieve
Front-end
$.ajax({ url: 'http://xxx.com', type: 'post', xhrFields:{ withCredentials:true }, data: {}, success: function(res){ }, error: function(){ alert('服务器发生错误!'); } });
Server (configured in the program entry file)
header('Access-Control-Allow-Origin: http://xxx.com'); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
The above is the entire content of this article, I hope it will be useful for everyone’s learning Help, please pay attention to the PHP Chinese website for more related content!
Related recommendations:
jQuery AJAX PHP MySQL development search function without jump or refresh
For config/index in vue. js: Detailed explanation of configuration
The above is the detailed content of Introduction to how Ajax implements cross-domain access. For more information, please follow other related articles on the PHP Chinese website!