Home Web Front-end JS Tutorial AJAX uses proxy, JSONP, and XHR2 to achieve cross-domain

AJAX uses proxy, JSONP, and XHR2 to achieve cross-domain

Apr 26, 2018 pm 02:43 PM
ajax javascript jsonp

This time I will bring you AJAX using proxies, JSONP, and XHR2 to achieve cross-domain, and AJAX using proxies, JSONP, and one time. Domain: The domain is the security boundary of the WIN2K network system. We know that the most basic unit of a computer network is a "domain". This is not unique to WIN2K, but Active Directory can run through one or more domains. On an independent computer, a domain refers to the computer itself. A domain can be distributed in multiple physical locations. At the same time, a physical location can be divided into different network segments into different domains. Each domain has its own security policy and its relationship with Trust relationships with other domains. When multiple domains are connected through trust relationships, Active Directory can be shared by multiple trusting domains.

Due to the need to use AJAX to request requests under other domain names at work, access will be denied. This is because based on security considerations, AJAX can only access local resources and cannot access cross-domain resources.

For example, if your website domain name is aaa.com, and you want to request the content in the bbb.com domain name through AJAX, the browser will consider it unsafe and deny access.

There will be several situations where cross-domain problems occur:

#The background searched for a solution on Baidu to solve this problem, and a total of three solutions were summarized: Proxy, JSONP, XHR2 (XMLHttpRequest Level 2).

The first method is proxy: This method is to obtain the content under other domain names through the background (ASP, PHP, JAVA, ASP.NET), and then return the obtained content to the front end, so that in the same under the domain name, so there will be no cross-domain problems.

Implementation code: Create an AJAX request (the page address is: http://localhost/ajax/proxy.html)

var request = null;
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}else{
request = new ActiveXObject("Microsoft.XMLHttp");
}
request.onreadystatechange = function(){
console.log(this.readyState);
if(this.readyState===4 && this.status===200){
var resultObj = eval("("+this.responseText+")"); //将返回的文本数据转换JSON对象
document.getElementById("box").innerHTML = resultObj.name+":"+resultObj.sex; //将返回的内容显示在页面中
}
}
request.open("POST","proxy.php",true);
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send("name=吕铭印&sex=男");
Copy after login

Create an AJAX request.

proxy.php code

header("Content-type:text/html;charset=utf-8");
$url = "http://localhost:63342/ajax/proxy.js";
$contents = file_get_contents($url);
echo $contents;
Copy after login
Use the php code to obtain the proxy.js file under localhost:63342.

proxy.js code

{
name : "吕铭印",
sex : "男"
}
Copy after login
proxy.html running result

##At this point, access is achieved using the proxy files between different domains.

First use AJAX in proxy.html to access the proxy.php file in the background. Then after proxy.php receives the request, it accesses the proxy.js file in localhost:63342. After obtaining the content of proxy.js, Return the content to the front-end page, which implements cross-domain functionality.

If you want to access multiple cross-domain files, you can tell the background proxy.php file the address of the file to be accessed in the form of a parameter.

The second method JSONP (only supports GET requests): Later, people discovered that there is no cross-domain impact when calling JS files, so the second method was derived.

is to load the data into a js file on the remote server for client calling and further processing.

jsonp.html

var url = "http://localhost:63342/ajax/jsonp.php?name=吕铭印&sex=男&callbackname=jsonp_callback"; //访问localhost:63342下的jsonp.php
var scriptTag = document.createElement("script"); //创建一个script标签
scriptTag.setAttribute("src",url); //设置script的src属性
document.body.appendChild(scriptTag); //将script标签添加到body中
//回调函数
var jsonp_callback = function(resultObj){
document.getElementById("box").innerHTML = resultObj.name+":"+resultObj.sex;
}
Copy after login
jsonp.php

$name = $_GET["name"];
$sex = $_GET["sex"];
$callbackname = $_GET["callbackname"]; //回调函数名称
echo "$callbackname({name:'$name',sex:'$sex'})";
Copy after login
jsonp.html Running results: Implementation principle: Since using script tags to call remote js files is not affected by cross-domain, you can create a script tag and access

remote files

through the src attribute.

Actually, this does not belong to AJAX, but it can achieve functions similar to AJAX.

The third method XMLHttpRequest Level 2: XMLHttpRequest Level 2 provided by HTML5 has implemented cross-domain access and some other new features

This requires adding the following code on the remote server side

header('Access-Control-Allow-Origin:*'); //*代表可访问的地址,可以设置指定域名
header('Access-Control-Allow-Methods:POST,GET');
Copy after login
In this way, you can use

regular AJAX code on the

client.

Summary: Proxy implementation is the most troublesome, but it is the most widely used. Any browser that supports AJAX can use this method.

JSONP is relatively simple, but only supports GET calls.

XHR2 is the simplest, but it only supports HTML5. If you are developing for mobile terminals, you can choose to use XHR2.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

JS encapsulation in the same domain, jsonp cross-domain (with code)

jQuery sets keyboard to switch text box focus

The above is the detailed content of AJAX uses proxy, JSONP, and XHR2 to achieve cross-domain. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

Asynchronous data exchange using Ajax functions Asynchronous data exchange using Ajax functions Jan 26, 2024 am 09:41 AM

How to use Ajax functions to achieve asynchronous data interaction With the development of the Internet and Web technology, data interaction between the front end and the back end has become very important. Traditional data interaction methods, such as page refresh and form submission, can no longer meet user needs. Ajax (Asynchronous JavaScript and XML) has become an important tool for asynchronous data interaction. Ajax enables the web to use JavaScript and the XMLHttpRequest object

See all articles