search
HomeWeb Front-endJS TutorialDetailed explanation of the use of AJAX and JavaScript

This time I will bring you a detailed explanation of the use of AJAX and JavaScript. What are the precautions when using AJAX and JavaScript? Here are practical cases, let’s take a look.

AJAX is not a JavaScript specification, it is just an abbreviation "invented" by a buddy: Asynchronous JavaScript and XML, which means using JavaScript to perform asynchronous network requests.

If you carefully observe the submission of a Form, you will find that once the user clicks the "Submit" button and the form begins to submit, the browser will refresh the page and then tell you in the new page whether the operation was successful or not. Failed. If unfortunately the network is too slow or for other reasons, you will get a 404 page.

This is how the Web works: one HTTP request corresponds to one page.

If you want the user to stay in the current page and make a new HTTP request at the same time, you must use JavaScript to send the new request. After receiving the data, use JavaScript to update the page. In this way, the user will feel You still stay on the current page, but the data can be continuously updated.

The earliest large-scale use of AJAX was Gmail. After the Gmail page was loaded for the first time, all remaining data relied on AJAX to update.

Writing a complete AJAX code in JavaScript is not complicated, but you need to pay attention: AJAX requests are executed asynchronously, that is, the response must be obtained through the callback function.
Writing AJAX on modern browsers mainly relies on XMLHttpRequestObject:

function success(text) {
 var textarea = document.getElementById('test-response-text');
 textarea.value = text;
}
function fail(code) {
 var textarea = document.getElementById('test-response-text');
 textarea.value = 'Error code: ' + code;
}
var request = new XMLHttpRequest(); // 新建XMLHttpRequest对象
request.onreadystatechange = function () { // 状态发生变化时,函数被回调
 if (request.readyState === 4) { // 成功完成
  // 判断响应结果:
  if (request.status === 200) {
   // 成功,通过responseText拿到响应的文本:
   return success(request.responseText);
  } else {
   // 失败,根据响应码判断失败原因:
   return fail(request.status);
  }
 } else {
  // HTTP请求还在继续...
 }
}
// 发送请求:
request.open('GET', '/api/categories');
request.send();
alert('请求已发送,请等待响应...');

For lower versions of IE, you need to change to an ActiveXObject object:

function success(text) {
 var textarea = document.getElementById('test-ie-response-text');
 textarea.value = text;
}
function fail(code) {
 var textarea = document.getElementById('test-ie-response-text');
 textarea.value = 'Error code: ' + code;
}
var request = new ActiveXObject('Microsoft.XMLHTTP'); // 新建Microsoft.XMLHTTP对象
request.onreadystatechange = function () { // 状态发生变化时,函数被回调
 if (request.readyState === 4) { // 成功完成
  // 判断响应结果:
  if (request.status === 200) {
   // 成功,通过responseText拿到响应的文本:
   return success(request.responseText);
  } else {
   // 失败,根据响应码判断失败原因:
   return fail(request.status);
  }
 } else {
  // HTTP请求还在继续...
 }
}
// 发送请求:
request.open('GET', '/api/categories');
request.send();
alert('请求已发送,请等待响应...');

If you want to mix standard writing and IE writing, you can write like this:

var request;
if (window.XMLHttpRequest) {
 request = new XMLHttpRequest();
} else {
 request = new ActiveXObject('Microsoft.XMLHTTP');
}

By detecting whether the window object There is the XMLHttpRequest attribute to determine whether the browser supports the standard XMLHttpRequest. Note, do not use the browser's navigator.userAgent to detect whether the browser supports a certain JavaScript feature. One is because the string itself can be forged, and the other is to determine JavaScript through the IE version. Features will be very complex.

After creating the XMLHttpRequest object, you must first set the callback function of onreadystatechange. In the callback function, usually we only need to judge whether the request is completed by readyState === 4. If it is completed, then based on status === 200Determine whether it is a successful response.
XMLHttpRequestThe object's open() method has 3 parameters. The first parameter specifies whether it is GET or POST. The two parameters specify the URL address, and the third parameter specifies whether to use asynchronous. The default is true, so there is no need to write it.

Note, never specify the third parameter as false, otherwise the browser will stop responding , until the AJAX request is completed. If this request takes 10 seconds, then within 10 seconds you will find that the browser is in a "suspended death" state.

Finally call the send() method to actually send the request. The GET request does not require parameters, and the POST request requires the body part to be passed in as a string or FormData object.

Security restrictions

The URL in the above code uses a relative path. If you change to 'http://www.sina.com.cn/' and run it again, an error will definitely be reported. In the Chrome console, you can also see error message.

This is caused by the browser’s same-origin policy. By default, when JavaScript sends an AJAX request, the domain name of the URL must be exactly the same as the current page.

完全一致的意思是,域名要相同(www.example.comexample.com不同),协议要相同(http和https不同),端口号要相同(默认是:80端口,它和:8080就不同)。有的浏览器口子松一点,允许端口不同,大多数浏览器都会严格遵守这个限制。

那是不是用JavaScript无法请求外域(就是其他网站)的URL了呢?方法还是有的,大概有这么几种:

一是通过Flash插件发送HTTP请求,这种方式可以绕过浏览器的安全限制,但必须安装Flash,并且跟Flash交互。不过Flash用起来麻烦,而且现在用得也越来越少了。

二是通过在同源域名下架设一个代理服务器来转发,JavaScript负责把请求发送到代理服务器:
'/proxy?url=http://www.sina.com.cn'代理服务器再把结果返回,这样就遵守了浏览器的同源策略。这种方式麻烦之处在于需要服务器端额外做开发。

第三种方式称为JSONP,它有个限制,只能用GET请求,并且要求返回JavaScript。这种方式跨域实际上是利用了浏览器允许跨域引用JavaScript资源:


 <script></script>
 ...


...

JSONP通常以函数调用的形式返回,例如,返回JavaScript内容如下:
foo('data');这样一来,我们如果在页面中先准备好foo()函数,然后给页面动态加一个<script></script>节点,相当于动态读取外域的JavaScript资源,最后就等着接收回调了。

以163的股票查询URL为例,对于URL:http://api.money.126.net/data/feed/0000001,1399001?callback=refreshPrice,你将得到如下返回:
refreshPrice({"0000001":{"code": "0000001", ... });

因此我们需要首先在页面中准备好回调函数:

function refreshPrice(data) {
 var p = document.getElementById('test-jsonp');
 p.innerHTML = '当前价格:' +
  data['0000001'].name +': ' + 
  data['0000001'].price + ';' +
  data['1399001'].name + ': ' +
  data['1399001'].price;
}

最后用getPrice()函数触发:

function getPrice() {
 var
  js = document.createElement('script'),
  head = document.getElementsByTagName('head')[0];
 js.src = 'http://api.money.126.net/data/feed/0000001,1399001?callback=refreshPrice';
 head.appendChild(js);
}

就完成了跨域加载数据。

CORS

如果浏览器支持HTML5,那么就可以一劳永逸地使用新的跨域策略:CORS了。

CORS全称Cross-Origin Resource Sharing,是HTML5规范定义的如何跨域访问资源。

了解CORS前,我们先搞明白概念:

Origin表示本域,也就是浏览器当前页面的域。当JavaScript向外域(如sina.com)发起请求后,浏览器收到响应后,首先检查Access-Control-Allow-Origin是否包含本域,如果是,则此次跨域请求成功,如果不是,则请求失败,JavaScript将无法获取到响应的任何数据。

用一个图来表示就是:

假设本域是my.com,外域是sina.com,只要响应头Access-Control-Allow-Originhttp://my.com,或者是*,本次请求就可以成功。

可见,跨域能否成功,取决于对方服务器是否愿意给你设置一个正确的Access-Control-Allow-Origin,决定权始终在对方手中。

上面这种跨域请求,称之为“简单请求”。简单请求包括GET、HEAD和POST(POST的Content-Type类型 仅限application/x-www-form-urlencodedmultipart/form-datatext/plain),并且不能出现任何自定义头(例如,X-Custom: 12345),通常能满足90%的需求。

无论你是否需要用JavaScript通过CORS跨域请求资源,你都要了解CORS的原理。最新的浏览器全面支持HTML5。在引用外域资源时,除了JavaScript和CSS外,都要验证CORS。例如,当你引用了某个第三方CDN上的字体文件时:

/* CSS */
@font-face {
 font-family: 'FontAwesome';
 src: url('http://cdn.com/fonts/fontawesome.ttf') format('truetype');
}

如果该CDN服务商未正确设置Access-Control-Allow-Origin,那么浏览器无法加载字体资源。
对于PUT、DELETE以及其他类型如application/json的POST请求,在发送AJAX请求之前,浏览器会先发送一个OPTIONS请求(称为preflighted请求)到这个URL上,询问目标服务器是否接受:
OPTIONS /path/to/resource HTTP/1.1
Host: bar.com
Origin: http://my.com
Access-Control-Request-Method: POST

服务器必须响应并明确指出允许的Method:
HTTP/1.1 200 OK
Access-Control-Allow-Origin:
http://my.com
Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS
Access-Control-Max-Age: 86400

浏览器确认服务器响应的Access-Control-Allow-Methods头确实包含将要发送的AJAX请求的Method,才会继续发送AJAX,否则,抛出一个错误。

由于以POST、PUT方式传送JSON格式的数据在REST中很常见,所以要跨域正确处理POST和PUT请求,服务器端必须正确响应OPTIONS请求。

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

推荐阅读:

用history让ajax支持前进/后退/刷新

原生ajax与封装的ajax使用方法(附代码)

The above is the detailed content of Detailed explanation of the use of AJAX and JavaScript. 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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool