Home Web Front-end JS Tutorial Detailed introduction to Ajax cross-domain issues

Detailed introduction to Ajax cross-domain issues

Apr 02, 2018 am 09:25 AM
ajax introduce

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);
  }
 }
}
Copy after login

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'
Copy after login

跨域

通过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通过动态

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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.

PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions Feb 25, 2024 am 11:15 AM

PyCharm is a powerful Python integrated development environment with rich functions and tools that can greatly improve development efficiency. Among them, the replacement function is one of the functions frequently used in the development process, which can help developers quickly modify the code and improve the code quality. This article will introduce PyCharm's replacement function in detail, combined with specific code examples, to help novices better master and use this function. Introduction to the replacement function PyCharm's replacement function can help developers quickly replace specified text in the code

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:

What is Dogecoin What is Dogecoin Apr 01, 2024 pm 04:46 PM

Dogecoin is a cryptocurrency created based on Internet memes, with no fixed supply cap, fast transaction times, low transaction fees, and a large meme community. Uses include small transactions, tips, and charitable donations. However, its unlimited supply, market volatility, and status as a joke coin also bring risks and concerns. What is Dogecoin? Dogecoin is a cryptocurrency created based on internet memes and jokes. Origin and History: Dogecoin was created in December 2013 by two software engineers, Billy Markus and Jackson Palmer. Inspired by the then-popular "Doge" meme, a comical photo featuring a Shiba Inu with broken English. Features and Benefits: Unlimited Supply: Unlike other cryptocurrencies such as Bitcoin

Detailed introduction of Samsung S24ai functions Detailed introduction of Samsung S24ai functions Jun 24, 2024 am 11:18 AM

2024 is the first year of AI mobile phones. More and more mobile phones integrate multiple AI functions. Empowered by AI smart technology, our mobile phones can be used more efficiently and conveniently. Recently, the Galaxy S24 series released at the beginning of the year has once again improved its generative AI experience. Let’s take a look at the detailed function introduction below. 1. Generative AI deeply empowers Samsung Galaxy S24 series, which is empowered by Galaxy AI and brings many intelligent applications. These functions are deeply integrated with Samsung One UI6.1, allowing users to have a convenient intelligent experience at any time, significantly improving the performance of mobile phones. Efficiency and convenience of use. The instant search function pioneered by the Galaxy S24 series is one of the highlights. Users only need to press and hold

See all articles