Home > Web Front-end > JS Tutorial > body text

Introduction to how Ajax implements cross-domain access

不言
Release: 2018-07-13 15:52:53
Original
1246 people have browsed it

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?

Solution

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('请求失败');
    }
});
Copy after login

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('服务器发生错误!');
    }
});
Copy after login
  • 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');
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!