发送Ajax GET和POST请求

使用GET或POST HTTP请求从服务器异步加载数据。 设置数据类型(xml,json,脚本,文本,html)并解码返回的数据


以下帮助函数允许通过GET方法发送Ajax请求-等效于jQuery的$.get()。 其url参数必须包含完整的请求路径,包括所有GET参数:


function getAjax(url, success) {
    var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    xhr.open('GET', url);
    xhr.onreadystatechange = function() {
        if (xhr.readyState>3 && xhr.status==200) success(xhr.responseText);
    };
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.send();
    return xhr;
}

// example request
getAjax('http://foo.bar/?p1=1&p2=Hello+World', function(data){ console.log(data); });
      

请求标头X-Requested-With允许服务器端框架(例如Django或RoR)识别Ajax请求。 它是可选的,但很有用。


getAjax('http://foo.bar/?p1=1&p2=Hello+World', function(data){
    var json = JSON.parse(data);
    console.log(json);
});
      

如果返回的JSON字符串可能无效,则将解析器包装到try-catch语句中。

发送POST请求非常相似(jQuery中的$.post())。 但是,有很多可用的选项-超过一个帖子所能涵盖的范围。 这是一个有用的帮助程序功能,可以帮助您入门:


function postAjax(url, data, success) {
  var params = typeof data == 'string' ? data : Object.keys(data).map(
          function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }
      ).join('&');

  var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
  xhr.open('POST', url);
  xhr.onreadystatechange = function() {
      if (xhr.readyState>3 && xhr.status==200) { success(xhr.responseText); }
  };
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send(params);
  return xhr;
}

// example request
postAjax('http://foo.bar/', 'p1=1&p2=Hello+World', function(data){ console.log(data); });

// example request with data object
postAjax('http://foo.bar/', { p1: 1, p2: 'Hello World' }, function(data){ console.log(data); });
      

Mozilla开发人员网络提供了许多有趣的Ajax示例和解决方案。 可以以各种格式发送数据,例如xml,json,脚本,文本和html。 现代浏览器允许发送文件并提供表单序列化工具。