/* 封裝ajax函數
* @param {string}opt.type http連接的方式,包括POST和GET兩種方式
* @param {string}opt.url 發送請求的url
* @param {boolean}opt.async 是否爲異步請求,true爲異步的,false爲同步的
* @param {object}opt.data 發送的參數,格式爲對象類型
* @param {function}opt.success ajax發送並接收成功調用的回調函數
* @param {function}opt.error ajax發送並接收失敗調用的回調函數
*/
function ajax(opt) {
opt = opt || {};
opt.method = opt.method.toUpperCase() || 'POST';
opt.url = opt.url || '';
opt.async = opt.async || true;
opt.data = opt.data || null;
opt.success = opt.success || function () {};
opt.error = opt.error || function () {};
var xhr = new plus.net.XMLHttpRequest();
xhr.onloadstart = function(){
console.log("開始請求")
}
xhr.onprogress = function(){
console.log("請求傳輸");
}
xhr.onabort = function(){
console.log("請求中斷");
}
xhr.onerror = function(){
console.log("請求錯誤")
}
xhr.ontimeout = function(){
console.log("請求超時")
}
xhr.onloadend = function(){
console.log("請求結束");
}
var params = [];
for (var key in opt.data){
params.push(key + '=' + opt.data[key]);
}
var postData = params.join('&');
if (opt.method.toUpperCase() === 'POST') {
xhr.open(opt.method, opt.url, opt.async);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
xhr.send(postData);
}
else if (opt.method.toUpperCase() === 'GET') {
xhr.open(opt.method, opt.url + '?' + postData, opt.async);
xhr.send();
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
opt.success(eval("("+xhr.responseText+")"));
}else if(xhr.readyState == 4){
console.log(xhr.status)
opt.error(xhr.staus);
}
};
}
注意:xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
1.在發起請求時,未加入charset=utf-8有可能造成,前端發送數據的 "編碼方式" 與後臺接收數據的 "解碼方式" 不同,導致訪問不到或時間過長
2.有可能遇到跨域問題,可以在java服務器controller中,加入如下代碼解決問題
response.setHeader("Access-Control-Allow-Origin", "*");