js Ajax函数封装及使用
    		       		warning:
    		            这篇文章距离上次修改已过449天,其中的内容可能已经有所变动。
    		        
        		                
                
// 简单的Ajax函数封装
function ajax(url, method, data, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open(method, url, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      callback(xhr.responseText);
    }
  };
  if (method === 'POST') {
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  }
  xhr.send(data);
}
 
// 使用封装后的ajax函数
var url = 'https://api.example.com/data';
var method = 'GET'; // 或者 'POST'
var data = 'key1=value1&key2=value2'; // POST请求时使用
 
ajax(url, method, data, function(response) {
  console.log('收到服务器响应:', response);
});这段代码定义了一个ajax函数,它接受url、method、data和callback作为参数,并执行HTTP请求。使用时,只需调用ajax函数并提供必要的参数即可。这是一个非常基础的Ajax函数封装示例,适合作为学习如何使用XMLHttpRequest对象进行网络通信的起点。
评论已关闭