javascript – 如何发出AJAX请求以发布JSON数据并处理响应

前端之家收集整理的这篇文章主要介绍了javascript – 如何发出AJAX请求以发布JSON数据并处理响应前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要将 JSON数据发布到URL并处理响应,这也是JSON数据.如何使用vanilla javascript,即没有第三方库?我还需要设置请求标头.请有人给我一个如何做到这一点的例子?

解决方法

好以下是如何在vanilla javascript中发出GET和POST请求,即没有像jQuery这样的第三方库,包括如何设置请求标头:
  1. // Just to namespace our functions and avoid collisions
  2. var _SU3 = _SU3 ? _SU3 : new Object();
  3.  
  4. // Does a get request
  5. // url: the url to GET
  6. // callback: the function to call on server response. The callback function takes a
  7. // single arg,the response text.
  8. _SU3.ajax = function(url,callback){
  9. var ajaxRequest = _SU3.getAjaxRequest(callback);
  10. ajaxRequest.open("GET",url,true);
  11. ajaxRequest.setRequestHeader('X-Requested-With','XMLHttpRequest');
  12. ajaxRequest.send(null);
  13. };
  14.  
  15. // Does a post request
  16. // callback: the function to call on server response. The callback function takes a
  17. // single arg,the response text.
  18. // url: the url to post to
  19. // data: the json obj to post
  20. _SU3.postAjax = function(url,callback,data) {
  21. var ajaxRequest = _SU3.getAjaxRequest(callback);
  22. ajaxRequest.open("POST",true);
  23. ajaxRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  24. ajaxRequest.setRequestHeader("Connection","close");
  25. ajaxRequest.send("data=" + encodeURIComponent(data));
  26. };
  27.  
  28. // Returns an AJAX request obj
  29. _SU3.getAjaxRequest = function(callback) {
  30.  
  31. var ajaxRequest;
  32.  
  33. try {
  34. ajaxRequest = new XMLHttpRequest();
  35. } catch (e) {
  36. try {
  37. ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
  38. } catch (e) {
  39. try {
  40. ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
  41. } catch (e){
  42. return null;
  43. }
  44. }
  45. }
  46.  
  47. ajaxRequest.onreadystatechange = function() {
  48. if (ajaxRequest.readyState == 4) {
  49. // Prob want to do some error or response checking,but for
  50. // this example just pass the responseText to our callback function
  51. callback(ajaxRequest.responseText);
  52. }
  53. };
  54.  
  55.  
  56. return ajaxRequest;
  57.  
  58. };

像这样使用它:

  1. function processResponse(responseText) {
  2. // Response text is a json:
  3. var obj = JSON.parse(responseText) // won't work all browsers,there are alternatives
  4. // Do something with obj
  5. ....
  6. }
  7.  
  8. var jsonToPost = .... // whatever your json is
  9. var url = ... // the URL to post to
  10.  
  11. _SU3.postAjax(url,processResponse,jsonToPost);

猜你在找的Ajax相关文章