GET和POST两种方式的 原生ajax提交数据

创建ajax过程

(1)创建XMLHttpRequest对象,也就是创建一个异步调用对象.

(2)创建一个新的HTTP请求,并指定该HTTP请求的方法、URL及验证信息.

(3)设置响应HTTP请求状态变化的函数.

(4)发送HTTP请求.

(5)获取异步调用返回的数据.

(6)使用JavaScript和DOM实现局部刷新.

//gat方式发送ajax请求
function getmethod(){ var xhr=getXhr(); xhr.open('get','/a?name=xiaozhi'); xhr.send(null);//get方式 不能省略send 方法,在参数里面写一个null即可 xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ console.log(xhr.responseText); } } }
//post方式发送ajax请求 function postmethod(){ var xhr=getXhr(); xhr.open('post','/a');   xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send('name=xiaozhi'); xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ console.log(xhr.responseText); } } } function getXhr(){ var xhr=null; if(window.XMLHttpRequest){ //其他浏览器 xhr=new XMLHttpRequest(); }else{ //IE8及之前版本浏览器 xhr = new ActiveXObject('Microsoft.XMLHttp'); } return xhr; }

  数据直接写死啦,到时候可以传参改变数据。

posted @ 2018-02-22 10:54  小智是小白  阅读(232)  评论(0)    收藏  举报