<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type="text/javascript"> function createAjax() { var request=false; //window 对象中有XMLHttpRequest存在 就是非ie,包括ie7,ie8 if(window.XMLHttpRequest) { request=new XMLHttpRequest(); if(request.overrideMimeType) request.overrideMimeType("text/xml"); } //window对象中有ActiveXObject属性存在就是ie低版本 else if(window.ActiveXObject) { var versions=['Microsoft.XMLHTTP','Msxml2.XMLHTTP','MSXML.XMHTTP']; for(var i=0;i<versions.length;i++) try{ request=new ActiveXObject(versions[i]); if(request) return request; } catch(e){ request=false; } } return request; } //注意:每次请求都要使用一个新的XMLHttpRequest,去除缓存 var ajax=null; function show() { var ajobj=document.getElementById("aj")//返回的是对象 ajax=createAjax(); ajax.onreadystatechange=function()//与服务器交互监听返回的数据状态 { //alert("###"+ajax.readyState);//弹出五次说明五种状态 0未初始化 1读取中 2已读取 3交互中 4完成 if(ajax.readyState==4) { if(ajax.status==200)//服务器返回的状态码eg:404 "文件未找到",200 "成功" { var data=ajax.responseText;//接受返回的数据 alert(data); ajobj.innerHTML=data; eval("var obj="+data); alert(obj.one); alert(obj.two); alert(obj.three); } else alert("页面请求失败!"); } } //请求数据get/post 如果是xml另算 get方式,则php部分也要用get接受参数,true为异步传输,math防止缓存 // ajax.open("get","server.php?name=ljf&qq=839471500&math=1"+Math.random(),true); // ajax.send(null);//必须执行即使发送null //post方法请求,服务器端用post接受, ajax.open("post","server.php",true); ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); ajax.send("name=ljf&qq=839471500"); } </script> </head> <body> <input type="button" οnclick="show()" value="request" /> <div id="aj"></div> </body> </html>
<?php //$str="{$_POST['name']}----{$_POST['qq']}---\n"; //$file=fopen("save.txt","a");//追加的方式打开 //fwrite($file,$str); //fclose($file); $arr=array("one"=>"111","two"=>"222","three"=>"333"); echo json_encode($arr); ?>