【Ajax】ajax 基本使用 / 跨域问题 / get和post
    		       		warning:
    		            这篇文章距离上次修改已过450天,其中的内容可能已经有所变动。
    		        
        		                
                Ajax基础使用:
// 创建一个新的XMLHttpRequest对象
var xhr = new XMLHttpRequest();
 
// 配置请求类型、URL 以及是否异步处理
xhr.open('GET', 'http://example.com/api/data', true);
 
// 设置请求完成的回调函数
xhr.onreadystatechange = function () {
  // 请求完成并且响应状态码为200
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      // 处理请求响应的数据
      console.log(xhr.responseText);
    } else {
      // 处理错误情况
      console.error('请求失败,状态码:' + xhr.status);
    }
  }
};
 
// 发送请求
xhr.send();Ajax处理跨域问题:
- JSONP:只支持GET请求,通过动态创建<script>标签发送请求。
- CORS:服务器需要设置适当的CORS头部,如Access-Control-Allow-Origin。
- 代理服务器:在服务器端创建一个代理,所有Ajax请求首先发送到这个代理,由代理转发请求到目标服务器。
- 使用服务端代理:在服务器端设置一个接口,前端发送Ajax请求到这个服务器端接口,由服务器代理发送真正的请求到目标URL。
Ajax GET和POST请求:
// GET请求
xhr.open('GET', 'http://example.com/api/data?param=value', true);
xhr.send();
 
// POST请求
xhr.open('POST', 'http://example.com/api/data', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 设置请求头
xhr.send('param=value');以上代码展示了如何使用Ajax发送GET和POST请求,以及处理跨域问题的基本方法。
评论已关闭