[TOC]
>[success] # ajax工具函數封裝
<br/>
ajax函數封裝后可以很方便的使用,不需要每次都重新寫一遍重復的代碼
<br/>
>[success] ## 簡單版(post、get函數)
<br/>
簡單版需要2個函數:`post` 函數和`get`函數,看著臃腫,里面暫時沒有做`數據類型的判斷`
<br/>
>[success] ### 前端代碼
<br/>
1. index.html
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./ajax.js"></script>
<script>
window.onload = function () {
// get請求
document.querySelector('.get').onclick = function () {
get('./backSendData.php', 'name=jack&friend=rose', function (data) {
console.log(data, 'get')
})
}
// post請求
document.querySelector('.post').onclick = function () {
post('./backSendData.php', 'name=jack&friend=rose', function (data) {
console.log(data, 'post')
})
}
}
</script>
</head>
<body>
<h2>測試工具函數</h2>
<input class="get" type="button" value="測試get">
<input class="post" type="button" value="測試post">
</body>
</html>
~~~
2. ajax.js
~~~
/**
* ajax工具函數-get
* @param {*} url
* @param {*} data (key1=value1&key2=value2)
* @param {*} success
*/
function get (url, data, success) {
// 創建異步對象
var xhr = new XMLHttpRequest();
// 請求行
if (data) { // 判斷是否有參數沒有參數就不拼接?
url += '?';
url += data;
}
xhr.open('get', url)
// 請求頭(get可以省略)
// 回調函數
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// 把接口數據返回到使用該函數處
success(xhr.responseText);
}
}
// 請求主體 發送
xhr.send(null)
}
/**
* ajax工具函數-post
* @param {*} url
* @param {*} data (key1=value1&key2=value2)
* @param {*} success
*/
function post (url, data, success) {
// 創建異步對象
var xhr = new XMLHttpRequest();
// 請求行
xhr.open('post', url);
// 請求頭(get可以省略,post不傳參數也可以不寫)
if (data) {
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
}
// 回調函數
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// 調用傳入的回調函數
success(xhr.responseText);
}
}
// 請求主體 發送
xhr.send(data);
}
~~~
<br/>
>[success] ### 后端代碼
<br/>
1. backSendData.php
~~~
<?php
echo '<h2>get</h2>';
print_r($_GET);
echo '<h2>post</h2>';
print_r($_POST);
?>
~~~
<br/>
>[success] ## 改進版(根據參數來決定請求的接口類型)
<br/>
改進后的只需要`一個函數`傳入不同的參數即可,缺點:參數必須要有序,順序不對就會報錯,里面暫時沒有做`數據類型的判斷`
<br/>
>[success] ### 前端代碼
<br/>
1. index.html
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./ajax.js"></script>
<script>
window.onload = function () {
// 根據參數來決定請求接口類型
document.querySelector('.ajax_test').onclick = function () {
ajax_test('./backSendData.php', 'post', 'name=葫蘆娃&food=胡蘿卜', function (data) {
console.log(data, 'asda')
})
}
}
</script>
</head>
<body>
<h2>測試工具函數</h2>
<input class="ajax_test" type="button" value="測試ajax_test">
</body>
</html>
~~~
<br/>
2. ajax.js
~~~
/**
* 根據傳入的類型來決定請求接口類型
* @param {*} url 接口url
* @param {*} type 請求類型
* @param {*} data 接口參數(key1=value1&key2=value2)
* @param {*} success 回調函數
*/
function ajax_test (url, type, data, success) {
var xhr = new XMLHttpRequest();
// 如果是get,并且有參數才設置
if (type === 'get' && data) {
url += "?";
url += data;
data = null; // 這樣最后直接send data即可
}
xhr.open(type, url);
// 如果是post,并且有參數才設置
if (type == 'post' && data) {
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
success(xhr.responseText)
}
}
xhr.send(data);
}
~~~
<br/>
>[success] ## 最終版
<br/>
將`參數`修改為對象的方式易于維護,而且里面做了`數據類型的判斷`
<br/>
>[success] ### 前端代碼
<br/>
1. index.html
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./ajax.js"></script>
<script>
window.onload = function () {
// 只傳一個參數
document.querySelector('.ajax').onclick = function () {
ajax({
url: './backSendData.php',
type: 'post',
data: 'name=葫蘆娃&food=胡蘿卜',
success: function (data) {
console.log(data, 'aoligei')
}
})
}
}
</script>
</head>
<body>
<h2>測試工具函數</h2>
<input class="ajax" type="button" value="測試ajax">
</body>
</html>
~~~
<br/>
2. ajax.js
~~~
/**
* ajax工具函數
* @param {*} option 參數為對象,值為以下內容
* @param {*} url 接口url
* @param {*} type 請求類型
* @param {*} data 接口參數(key1=value1&key2=value2)
* @param {*} success 回調函數
*/
function ajax (option) {
var xhr = new XMLHttpRequest();
// 如果是get,并且有參數才設置
if (option.type === 'get' && option.data) {
option.url += "?";
option.url += option.data;
option.data = null; // 這樣最后直接send data即可
}
xhr.open(option.type, option.url);
// 如果是post,并且有參數才設置
if (option.type == 'post' && option.data) {
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var type = xhr.getResponseHeader("Content-Type"); // 獲取服務器在header上的信息
if (type.indexOf('json') != -1) { // 判斷為json格式信息
option.success(JSON.parse(xhr.responseText))
} else if (type.indexOf('xml') != -1) { // 判斷為xml格式信息
option.success(xhr.responseXML)
} else { // 普通字符串
option.success(xhr.responseText)
}
}
}
xhr.send(option.data);
}
~~~
<br/>
>[success] # ajax補充
<br/>
1. 設置返回的數據類型
~~~
'后端'不加'header'情況下,'前端'無法取到'Content-Type'進行條件判斷,所以默認返回的數據會是普通
字符串,為了解決這種問題需要設置'responseType'為'json',如果是'jquery'的'ajax',設置'dataType'
為'json/xml'等等
~~~
<br/>
2. 跨域
~~~
解決辦法:
1. 'CORS','html5'支持,低版本瀏覽器用不了
2. 'JSONP',在'jquery'中如果'請求跨域的接口'需要設置'dataType'為'jsonp'
~~~
- 基本概念
- 服務器
- PHP學習
- PHP根據數據生成頁面
- form表單提交數據到服務器
- form表單查詢信息詳情頁
- 列表渲染展示以及跳轉詳情
- PHP拆分寫法
- form表單提交
- get方式提交數據補充
- post方式提交數據
- post上傳文件
- 請求報文和響應報文基本概念
- XMLHTTPRequest對象的基本使用
- 回調函數&獲取返回的數據
- ajax發送get請求
- ajax驗證用戶是否存在邏輯
- ajax發送post請求
- 新浪云使用方法
- onload 和 onreadystatechange
- XML格式
- 服務器返回XML格式數據
- JSON格式
- 服務器返回JSON格式數據
- ajax工具函數封裝
- js模板引擎
- 跨域解決方案
- JSONP
- CORS解決跨域
- 下載文件功能