JavaScript之ajax

 1 // 原生ajax
 2 // get方法向服务器请求数据
 3 function getData (url, callback) {
 4   var request = new XMLHttpRequest()
 5   request.open('GET', url)
 6   request.onreadystatechange = function () {
 7     if (request.readyState === 4 && request.status === 200) {
 8       var type = request.getResponseHeader('Content-Type') // 获得响应头
 9       if (type.match(/^text/)) // 确保响应是文本
10         callback(request.responseText)  // 把它传递给回调函数
11     }
12   }
13   request.send(null) // get请求没有请求主体
14 }
15 
16 
17 // GET方法提交只读数据,将数据拼接在URL后。有数据大小限制,存在安全性问题。
18 
19 // POST方法提交表单,无数据大小限制,安全可靠。
20 // 使用JSON编码主体发起HTTP POST请求
21 function postJSON(url, data, callback) {
22   var request = new XMLHttpRequest()
23   request.open('POST', url)
24   request.onreadystatechange = function () { // 事件监听程序
25     if (request.onreadystatechange === 4 && callback) {
26       callback(request)
27     }
28   }
29   request.setRequestHeader('Content-Type', 'application/json')
30   request.send(JSON.stringify(data))   // 有主体
31 }
32 
33 // 使用JQuery库的ajax方法
34 $.ajax({
35   url: '/test1.php',
36   type: 'POST', // get
37   async: true, //异步加载,默认为true
38   data: {
39     name: 'mdj',
40     age: '11' 
41   }, // 向服务器提交的数据
42   dataType: 'json', //返回的数据格式
43   beforeSend: function (xhr) {
44     console.log(xhr)
45     console.log('发送前')
46   },
47   success: function () {},
48   error: function () {},
49   complete: function () {
50   console.log('结束')
51   }
52 })

猜你喜欢

转载自www.cnblogs.com/i-Leo/p/9213637.html