1. function ajax(options, callback){
    2. var xmlhttp = null;
    3. var url = options.url;
    4. var method = options.method.toLocaleLowerCase() || 'get';
    5. var data = options.data
    6. if (window.XMLHttpRequest) { // 1.创建XMLHttpRequest对象
    7. xmlhttp = new XMLHttpRequest();
    8. if (xmlhttp.overrideMimeType) { //针对某些特定版本的mozillar浏览器的BUG进行修正
    9. xmlhttp.overrideMimeType("text/xml");
    10. }
    11. } else if (window.ActiveXObject) { //针对IE6,IE5.5,IE5
    12. var activexName = [ "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ]; //两个可以用于创建XMLHTTPRequest对象的控件名称,保存在一个js的数组中
    13. for ( var i = 0; i < activexName.length; i++) {
    14. try {
    15. xmlhttp = new ActiveXObject(activexName[i]); //取出一个控件名进行创建,如果创建成功就终止循环 ,如果创建失败,回抛出异常,然后可以继续循环,继续尝试创建
    16. if(xmlhttp){
    17. break;
    18. }
    19. } catch (e) {
    20. console.log(e)
    21. }
    22. }
    23. }
    24. var paramArr = []
    25. var encodeData
    26. if (data instanceof Object) {
    27. for (var key in data) {
    28. paramArr.push( encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) ) // 参数拼接需要通过 encodeURIComponent 进行编码
    29. }
    30. encodeData = paramArr.join('&')
    31. }
    32. if (method === 'get') { // 检测 url 中是否已存在 ? 及其位置
    33. var index = url.indexOf('?')
    34. if (index === -1) url += '?'
    35. else if (index !== url.length -1) url += '&' // 拼接 url
    36. url += encodeData
    37. }
    38. xmlhttp.open(method, url); // 2.使用open方法设置和服务器的交互信息
    39. if (method === 'get') xmlhttp.send(null) // 3.发送请求
    40. else {
    41. xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8'); // post 方式需要设置请求头
    42. xmlhttp.send(encodeData)
    43. }
    44. xmlhttp.onreadystatechange = function() { // 响应函数
    45. if(xmlhttp.readyState ==4 && xmlhttp.status==200) {
    46. callback(xmlhttp.responseText)
    47. }
    48. }
    49. }
    50. function getData(data){
    51. console.log('请求成功', data)
    52. }
    53. ajax({
    54. url: 'your request url',
    55. method: 'get',
    56. data: {
    57. name: 'rashomon',
    58. age: 13
    59. }
    60. },getData)