原生js的ajax请求

来源:互联网 发布:网络阅读利弊的辩论 编辑:程序博客网 时间:2024/05/21 22:52
//针对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,单独书写代码

参考:http://www.cnblogs.com/cythia/p/6978323.html

原创粉丝点击