简单封装一个Ajax函数,方便在以后的开发中可以直接使用。代码如下:

    1. function myAjaxAdv(obj) {
    2. var defaults = {
    3. type: 'get',
    4. url: '#',
    5. dataType: 'json',
    6. data: {},
    7. sync: true,
    8. success: function(result) {}
    9. }
    10. for (var key in obj) {
    11. defaults[key] = obj[key];
    12. }
    13. //兼容IE浏览器
    14. var xhr = null;
    15. if (window.XMLHttpRequest) {
    16. xhr = new XMLHttpRequest();
    17. } else {
    18. xhr = new ActiveXObject('Microsoft.XMLHTTP');
    19. }
    20. //得到params
    21. var parmas = "";
    22. for (var attr in defaults.data) {
    23. parmas += attr + "=" + defaults.data[attr] + "&";
    24. }
    25. if (parmas) {
    26. parmas = parmas.substring(0, parmas.length - 1);
    27. }
    28. //准备发送
    29. if (defaults.type == 'get') {
    30. defaults.url += '?' + parmas;
    31. }
    32. xhr.open(defaults.type, defaults.url, defaults.sync);
    33. //执行发送
    34. if (defaults.type == 'get') {
    35. xhr.send(null);
    36. } else if (defaults.type == 'post') {
    37. xhr.setRequestHeader('Content-type","application/x-www-form-urlencoded');
    38. xhr.send(parmas);
    39. }
    40. //判断异步或同步,获取返回值
    41. if (defaults.sync) {
    42. xhr.onreadystatechange = function() {
    43. if (xhr.readyState == 4) {
    44. if (xhr.status == 200) {
    45. var result = null;
    46. if (defaults.dataType == 'json') {
    47. result = xhr.responseText;
    48. result = JSON.parse(result);
    49. } else if (defaults.dataType == 'xml') {
    50. result = xhr.responseXML;
    51. } else {
    52. result = xhr.responseText;
    53. }
    54. defaults.success(result);
    55. }
    56. }
    57. }
    58. } else {
    59. if (xhr.readyState == 4) {
    60. if (xhr.status == 200) {
    61. var result = null;
    62. if (defaults.dataType == 'json') {
    63. result = xhr.responseText;
    64. result = JSON.parse(result);
    65. } else if (defaults.dataType == 'xml') {
    66. result = xhr.responseXML;
    67. } else {
    68. result = xhr.responseText;
    69. }
    70. defaults.success(result);
    71. }
    72. }
    73. }
    74. }
    参数名 类型 说明
    type String 请求类型,默认为GET,有效值:POST
    url String 服务器接口请求地址
    dataType String 返回值类型,默认为JSON,有效值:XML,text
    data Object 请求的参数值,采用键值对形式。data:{ key: value }
    success Function 接口调用成功的回调函数
    sync Boolean 异步或同步请求。true为异步,false为同步。默认为true。

    示例代码:

    1. myAjaxAdv({
    2. url:'https://www.example.com',//仅为示例,并非真实地址
    3. type:'get',
    4. data:{
    5. key:value
    6. },
    7. success:function(result){
    8. console.log(result);
    9. }
    10. })