search
HomeWeb Front-endJS TutorialDetailed introduction to Ajax cross-domain issues

This time I will bring you a detailed introduction to Ajax cross-domain issues. What are the precautions for using Ajax cross-domain issues? The following is a practical case, let's take a look.

What is ajax

Ajax (Asynchronous JavaScript and XML) is a method that can request additional data from the server without refreshing the page. Technology, the emergence of ajax has brought a better user experience.

The core of Ajax is the XMLHttpRequest (XHR) object. XHR provides a smooth interface for sending requests to the server and parsing server responses. You can use the XHR object Get new data and insert the new data into the page through the DOM. Although the name contains XML, ajax communication has nothing to do with the data format; this technology can get data from the server without refreshing, but it does not have to be XML data, it can also be json.

XMLHttpRequest object

XHR usage

1. Create an XMLHttpRequest object

2. Send a request

1).Set the request line xhr.open()
2).POST requestNeed to set the request header xhr.setRequestHeader() POST The value of the request header Content-Type: application/x-www-form-urlencoded
3). Set the request body xhr.send() get request to pass null, post according to the situation

3. Process the server response

First determine whether the response status code and asynchronous object have been parsed.

Status code status returned by the server

1xx: Message
2xx: Success
3xx: Redirect
4xx: Request error
5xx: Server error

The status code of the asynchronous object readystate

0: The asynchronous object has been created
1 : The asynchronous object initialization is completed and the request is sent
2: Receive the original data returned by the server
3: The data is being parsed and the parsing will take time
4: The data parsing is completed and the data can be used

XML

Characteristics of XML, from a prestigious family, formulated by W3C, a data format that has been strongly recommended by Microsoft and IBM. XML refers to Extensible Markup Language (Extensible Markup Language), which is designed to To transmit and store data, HTML is designed to represent pages.

Grammar rules: Similar to HTML, they are all represented by tags

Special symbols: such as Using entity-transfer characters

Xml parsing requires front-end and back-end cooperation:
1. When the back-end returns, set the Content-Type value in the response header to application/xml
2. The front-end When the asynchronous object receives background data, remember to receive it in the form of xml, xhr.responseXML, and it returns an object object, the content is #document

JSON

JSON (JavaScript Object Notation), originated from the grassroots, is a subset of Javascript and is responsible for describing the data format. JSON itself is a string in a special format that can be converted into a js object and is used on the Internet. There is no one of the most widely used data formats to transmit data.

Grammar rules: Data is represented by key/value pairs, and the data is separated by commas. Parentheses save objects, square brackets save arrays, names and values ​​need to be enclosed in double quotes (this is a small difference from js).
Parsing/manipulating JSON in js:
1.JSON.parse(json string); Parse a json format string into a js object
2.JSON.stringify(js object); Convert a js object into a json format character String

Encapsulate an ajax yourself

function pinjieData(obj) {
 //obj 就相当于 {key:value,key:value}
 //最终拼接成键值对的字符串 "key:value,key:value"
 var finalData = "";
 for(key in obj){
  finalData+=key+"="+obj[key]+"&"; //key:value,key:value&
 }
 return finalData.slice(0,-1);//key:value,key:value
}
function ajax(obj) {
 var url = obj.url;
 var method = obj.method.toLowerCase();
 var success = obj.success;
 var finalData = pinjieData(obj.data);
 //finalData最终的效果key:value,key:value
 //1.创建xhr对象
 var xhr = new XMLHttpRequest();
 //get方法拼接地址,xhr.send(null)
 if (method=='get'){
  url = url + "?"+finalData;
  finalData = null;
 }
 //2.设置请求行
 xhr.open(method,url);
 // 如果是post请求,要设置请求头
 if (method=='post'){
  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
 }
 //3.发送
 xhr.send(finalData);
 //4.监听服务器返回的数据
 xhr.onreadystatechange = function () {
  if (xhr.status==200 && xhr.readyState==4){
   var result = null;
   //获取返回的数据类型
   var rType = xhr.getResponseHeader("Content-Type");
   if (rType.indexOf('xml')!=-1){
    result = xhr.responseXML;
   }else if(rType.indexOf('json')!=-1){
    // JSON.parse 的意思是 将 json格式的字符串
    //比如 [{ "src":"./images/nav0.png","content":"商品分类1"}]
    //转成js对象
    result = JSON.parse(xhr.responseText);
   }else{//当成普通的字符串去处理
    result = xhr.responseText;
   }
   //将这里解析好的数据交给页面去渲染
   success(result);
  }
 }
}

Use ajax in jQueryAPI jQuery ajax

jQuery provides us with a more convenient ajax package.

$.ajax({}) Can be configured to initiate an ajax request
$.get() Initiate an ajax request in get mode
$.post() Initiate ajax request in post mode
$ ('form').serialize() Serialize form (format key=val$key=val)

Parameter description

url :接口地址
type :请求方式(get/post)
timeout : 要求为Number类型的参数,设置请求超时时间(毫秒)
dataType: 应该是客户端传递给服务器一个值,告诉服务器如何进行处理:
data: 发送请求数据
beforeSend: 要求为Function类型的参数,发送请求前可以修改XMLHttpRequest对象的函数,例如添加自定义HTTP头。在beforeSend中如果返回false可以取消本次ajax请求.
success: 成功响应后调用
error: 错误响应时调用
complete: 响应完成时调用(包括成功和失败)

 //ajax===get
 $.ajax({
  url:'',
  data:'key=value&key=value',
  type:'get',
  success:function (result) {
   console.log(result);
  }
 });
//ajax===post
$.ajax({
  url:'',
  data:'key=value&key=value',
  type:'post',
  success:function (result) {
   console.log(result);
  }
 });
//$.get
$.get({
  url:'',
  data:'key=value&key=value',
  success:function (result) {
  console.log(result);
  }
});
//$.post
$.post({
  url:'',
  data:'key=value&key=value',
  success:function (result) {
  console.log(result);
  }
});
//在使用jQuery中ajax发送请求的时候,只需要在 dataType中写上jsonp即可实现ajax的跨域请求
 dataType:'jsonp'

跨域

通过XHR实现ajax通信的一个主要限制(相同域,相同端口,相同协议),来源于跨服安全策略,默认情况下,XHR只能请求同一域的资源,这是为了防止某些恶意的行为.

CORS跨域

CORS(cross-origin resource sharing,跨域源资源共享)定义了在跨域时,浏览器和服务器应该如何沟通.CORS允许一个域上的网络应用向另一个域提交跨域 AJAX 请求。实现此功能非常简单,只需由服务器发送一个响应标头即可。
CORS支持所有类型的HTTP请求.
服务器端对于CORS的支持,主要就是通过设置Access-Control-Allow-Origin来进行的。

JSONP

JSONP由回调函数和数据组成.JSONP只支持GET请求.JSONP的优势在于支持老式浏览器,以及可以向不支持CORS的网站请求数据.
JSONP通过动态<script>元素来使用,src属性知道一个跨域URL,JSONP是有效的JavaScript代码,浏览器可以跨域请求JS文件.<br/>优点:简单易用,可以直接访问响应文本,支持在浏览器和服务器之间双向通信.<br/>缺点:1.JSONP是从其他域加载代码执行,存在不安全风险.2.不好确定JSONP请求是否成败.</script>

通过修改document.domain来跨子域

使用window.name来进行跨域

HTML5中新引进 window.postMessage方法来跨域传送数据

flash

iframe

服务器设置代理页面

图像Ping

通过使用标签,利用网页可以从任何网页加载图像原理.
图像Ping常用于跟踪用户点击页面或动态广告曝光次数.

2个缺点:1.只支持GET请求.2.无法访问服务器的响应文本.只能用于浏览器与服务器间的单项通信.

var img = new Image();
img.onload = img.onerror = function (){
alert("Done!");
};
img.src = "";

comet

一种更高级的ajax技术.ajax是页面向服务器请求数据的技术.comet是服务器向页面推送数据的技术.

SSE (Server-Sent Events) 服务器发送事件

Web Sockets

Web Sockets的目标是在一个单独的持久链接上提供全双工,双向通信.

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

PHP+Ajax如何实现表格的实时编辑

用ajax实现session超时跳转到登录页面

The above is the detailed content of Detailed introduction to Ajax cross-domain issues. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools