原生javascript封装类似jquery的ajax请求跨域函数

原生javascript封装类似jquery的ajax请求跨域函数//定义局部变量varxmlhttp,type,url,async,dataType,data;//默认type为GETtype=trim.to

大家好,欢迎来到IT知识分享网。

在网上查看了很多js的ajax封装函数

发现大部分都没有实现跨域请求

所以跨域请求浏览器就会提示:No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

于是封装了一个跨域请求的ajax函数:

js代码:

[html] view plain copy

  1. function ajax(obj) {
  2. // 对实参处理
  3. obj = obj || {};
  4. // 定义局部变量
  5. var xmlhttp, type, url, async, dataType, data;
  6. // 默认type为GET
  7. type = trim(obj.type).toUpperCase() || ‘GET’;
  8. // 接口
  9. url = trim(obj.url) || window.location.href;
  10. // 默认为异步请求
  11. async = obj.async || true;
  12. // 设置跨域
  13. dataType = trim(obj.dataType).toUpperCase() || ‘HTML’;
  14. // 发送参数
  15. data = obj.data || {};
  16. // 删除左右空格
  17. function trim(str) {
  18. return str.replace(/^\s+|\s+$/g, “”);
  19. };
  20. // 定义格式化参数函数
  21. var formatParams = function() {
  22. if (typeof(data) == “object”) {
  23. var str = “”;
  24. for (var pro in data) {
  25. str += pro + “=” + data[pro] + “&”;
  26. }
  27. data = str.substr(0, str.length – 1);
  28. }
  29. if (type == ‘GET’ || dataType == ‘JSONP’) {
  30. if (url.lastIndexOf(‘?’) == -1) {
  31. url += ‘?’ + data;
  32. } else {
  33. url += ‘&’ + data;
  34. }
  35. }
  36. }
  37. // 第一步,创建xmlhttprequest对象用来和服务器交换数据。
  38. if (window.XMLHttpRequest) {
  39. //Chrome || Firefox
  40. xmlhttp = new XMLHttpRequest();
  41. } else {
  42. //IE
  43. xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”);
  44. }
  45. // 跨域请求
  46. if (dataType == ‘JSONP’) {
  47. if (typeof(obj.beforeSend) == ‘function’) obj.beforeSend(xmlhttp);
  48. var callbackName = (‘jsonp_’ + Math.random()).replace(“.”, “”);
  49. var oHead = document.getElementsByTagName(‘head’)[0];
  50. data.callback = callbackName;
  51. var ele = document.createElement(‘script’);
  52. ele.type = “text/javascript”;
  53. ele.onerror = function() {
  54. console.log(‘failed’);
  55. obj.error && obj.error(“failed”);
  56. };
  57. oHead.appendChild(ele);
  58. window[callbackName] = function(json) {
  59. oHead.removeChild(ele);
  60. window[callbackName] = null;
  61. obj.success && obj.success(json);
  62. };
  63. formatParams();
  64. ele.src = url;
  65. return;
  66. } else {
  67. formatParams();
  68. // 第二步,打开链接
  69. xmlhttp.open(type, url, async);
  70. // 设置响应头
  71. xmlhttp.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded;charset=utf-8”);
  72. if (typeof(obj.beforeSend) == ‘function’) obj.beforeSend(xmlhttp);
  73. // 第三步,发送请求
  74. xmlhttp.send(data);
  75. // 第四步,响应处理
  76. xmlhttp.onreadystatechange = function() {
  77. if (xmlhttp.status != 200) {
  78. console.log(xmlhttp.status + ‘failed’);
  79. obj.error && obj.error(xmlhttp.status + ‘failed’);
  80. return;
  81. }
  82. if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
  83. if (dataType == ‘JSON’) {
  84. try {
  85. res = JSON.parse(xmlhttp.responseText);
  86. } catch (e) {
  87. console.log(‘json格式错误’);
  88. obj.error(‘json格式错误’);
  89. }
  90. } else if (dataType == ‘XML’) {
  91. res = xmlhttp.responseXML;
  92. } else {
  93. res = xmlhttp.responseText;
  94. }
  95. obj.success && obj.success(res);
  96. }
  97. }
  98. }
  99. }

使用示例:

[html] view plain copy

  1. ajax({
  2. url: ”,
  3. type: ‘get’,
  4. dataType: ‘jsonp’,
  5. success: function(data) {
  6. },
  7. error: function() {
  8. }
  9. })
原生javascript封装类似jquery的ajax请求跨域函数

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/43047.html

(0)
上一篇 2024-04-19 14:26
下一篇 2024-04-19 20:26

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信