一般我們寫網頁的時候,如果用到 Ajax 請求伺服器,都是使用 JQuery 等已經封裝好的函式庫來調用,比較簡單。但是一般這些函式庫的功能很多,引入了太多我們用不到的東西,如果我們需要寫一個功能單一,簡單的頁面,完全用不到引用如此龐大的庫文件。本文我們主要跟大家分享原生JS寫Ajax的請求函數功能,希望能幫助大家。
我們可以簡單實作一個自己的Ajax 請求功能,具體的程式碼如下:
var ajax = {}; ajax.x = function () { if (typeof XMLHttpRequest !== 'undefined') { return new XMLHttpRequest(); } var versions = [ "MSXML2.XmlHttp.6.0", "MSXML2.XmlHttp.5.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.2.0", "Microsoft.XmlHttp" ]; var xhr; for (var i = 0; i < versions.length; i++) { try { xhr = new ActiveXObject(versions[i]); break; } catch (e) { } } return xhr; }; ajax.send = function (url, method, data, success,fail,async) { if (async === undefined) { async = true; } var x = ajax.x(); x.open(method, url, async); x.onreadystatechange = function () { if (x.readyState == 4) { var status = x.status; if (status >= 200 && status < 300) { success && success(x.responseText,x.responseXML) } else { fail && fail(status); } } }; if (method == 'POST') { x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); } x.send(data) }; ajax.get = function (url, data, callback, fail, async) { var query = []; for (var key in data) { query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); } ajax.send(url + (query.length ? '?' + query.join('&') : ''), 'GET', null, callback, fail, async) }; ajax.post = function (url, data, callback, fail, async) { var query = []; for (var key in data) { query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); } ajax.send(url,'POST', query.join('&'), callback, fail, async) };
##使用方法: GET
ajax.get('/test.php', {foo: 'bar'}, function(response,xml) { //success }, function(status){ //fail }); POST ajax.post('/test.php', {foo: 'bar'}, function(response,xml) { //succcess },function(status){ //fail });
var sendCmd = "?op_code=" + code + "&op_cmd=" + cmd; ajax.post('/control' + sendCmd,'',function(response,xml) { console.log('success'); }, function(status){ console.log('failed:' + status); });
以上是原生JS寫Ajax的請求函數功能的實例分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!