您现在的位置:首页 >> 前端 >> 内容

原生js的ajax请求

时间:2017/10/8 10:14:00 点击:

  核心提示://针对get方法var xhr = new XMLHttpRequest();xhr.open(get,getStar.php?starName=+name,true);xhr.send();xhr...
//针对get方法
var xhr = new XMLHttpRequest();
xhr.open("get",'getStar.php?starName='+name,true);
xhr.send();
xhr.onreadyStateChange=function () {
    if(readyState==4 && status==200){
      console.log(xhr.responseText);
    }
};
//针对post方法
var xhr = new XMLHttpRequest();
xhr.open("post","02.post.php",true);
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send("name=123");
xhr.onreadyStateChange=function () {
  if(readyState==4 && status==200){
    console.log(xhr.responseText);
  }
};

注意:
1.setRequestHeader()把指定首部设置为所提供的值。在设置任何首部之前必须先调用open()。设置header并和请求一起发送 (‘post’方法一定要 )
2.post请求一定要添加请求头才行不然会报错
3.open("method","URL",[asyncFlag],["userName"],["password"]) 建立对服务器的调用。method参数可以是GET、POST或PUT。url参数可以是相对URL或绝对URL。这个方法还包括3个可选的参数,是否异步,用户名,密码
4.send(content) 向服务器发送请求
5.需要兼容IE,单独书写代码

Tags:原生 生J JS S的 
作者:网络 来源:初漾的博客