概念理解html
建立Ajax面试
建立XMLHttpRequest对象ajax
var xhr; if (window.XMLHttpRequest){ //IE7+, Firefox, Chrome, Opera, Safari xhr=new XMLHttpRequest(); }else{ // 兼容 IE6, IE5 xhr=new ActiveXObject("Microsoft.XMLHTTP"); }
对于异步请求,没必要等待服务器响应,JS代码继续执行。
能够检测XHR对象的readyState属性,该属性表示请求/响应过程的当前活动阶段。服务器
0:未初始化。还没有调用open()方法。 1:启动。已经调用open()方法,还没有调用send()方法。 2:发送。已经调用send()方法,还没有接收响应。 3:接收。已经接收到部分响应。 4:完成。已经接收到所有响应数据。
只要readyState属性的值由一个值变成另外一个值,就会触发onreadyStatechange事件,利用这个事件来检测每次状态变化后readyState值,获取服务器的响应也在这个事件中处理。app
xhr.onreadyStatechange = function(){ If(xhr.readyState == 4){ if(xhr.status >=200 && xhr.status = 304){ alert(xhr.responseText); }else{ alert(“Request was unsuccessful: ”+ xhr.status); } } };
建立一个新的HTTP请求,并指定请求的方法、URL及异步(true)/同步(false)异步
xhr.open(method,url,async); 注意:open 的参数要牢记,不少面试官爱问这样的细节 1)method:请求的类型;GET 或 POST 2)url:文件在服务器上的位置 3)async:true(异步)或 false(同步) 注意:post请求必定要设置请求头的格式内容 xhr.open("post","ajax_test.html",true); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //使用XHR模仿表单提交 xhr.send("fname=Henry&lname=Ford");
发送HTTP请求async
xmlhttp.send(); 如果post请求,参数为做为请求主体发送的参数。 如果get请求,参数为null。
获取同步发送请求返回的数据post
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ alert(xhr.responseText); }else{ alert(“Request was unsuccessful: ”+ xhr.status); }