Ajax备忘

来源:互联网 发布:中国电子商务发展数据 编辑:程序博客网 时间:2024/06/16 15:12

一.ajax通过get方式返回txt

var http_request = false;function createRequest(url) {  //正对不同浏览器创建XMLHttpRequesthttp_request = false;if (window.XMLHttpRequest) { http_request = new XMLHttpRequest();if (http_request.overrideMimeType) {http_request.overrideMimeType("text/xml");}} else if (window.ActiveXObject) { try {http_request = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try {http_request = new ActiveXObject("Microsoft.XMLHTTP");   } catch (e) {}}}if (!http_request) {alert("不能创建XMLHTTP实例!");return false;}http_request.onreadystatechange = alertContents;   //指定回调函数http_request.open("GET", url, true);//构建 http_request.send(null);                //发送}

function alertContents() {                      //写回调函数if (http_request.readyState == 4) {if (http_request.status == 200) {
alert(http_request.responseText);   //这里写具体js方法} else {alert('您请求的页面发现错误');}}}

function check(){      //这里写触发事件的函数  if($("#txt")[0].value==""){  alert("请输入内容!");  $("#txt")[0].focus();    }  else{   createRequest("test.php"); //这里传输url,可以传递信息,如url="test.php?txt_name="+txt_name+"&txt_age="+txt_age; 在php中类似$_GET[txt_name]这样调用
                              //另外这个php文件不能用html标记,否则会把整个文档都返回  }}


二.ajax通过post方式返回txt

post与get都需要把传递的值写入"A="+A+"&B="+B 这样的字符串中,类似url的写法,在php用$_POST[A]这样调用。另外post还需要写一句
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 

<script language="javascript"> function saveUserInfo() {   var url = "test.php";   //var info   = "txt_name="+ txt_name +"txt_age="+ txt_age ; 在php中用$_POST[txt_name]这样调用   var info   = "txt=123";   var ajax = false;   if(window.XMLHttpRequest)  {        ajax = new XMLHttpRequest();      if (ajax.overrideMimeType)        {              ajax.overrideMimeType("text/xml");       }     }     else if (window.ActiveXObject)      {         try         {             ajax = new ActiveXObject("Msxml2.XMLHTTP");         }          catch (e)          {             try             {                 ajax = new ActiveXObject("Microsoft.XMLHTTP");              }               catch (e) {}           }     }      if (!ajax)      {          window.alert("不能创建XMLHttpRequest对象实例.");         return false;     }  ajax.onreadystatechange = function()      {          if (ajax.readyState == 4 && ajax.status == 200)        {             alert(ajax.responseText);           }      }      ajax.open("POST", url, true);     ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");     ajax.send(info);    } </script> 

二.ajax返回xml

返回xml和上面两种方法几乎是相同的,只不过是用responseXML代替responseText,返回的是一个xml对象,在js中可以如用如下的DOM属性来读出xml的内容:

documentElement  返回当前元素的根节点
ChindNodes  返回当前元素的所有子元素的数组
FirstChild        返回当前元素的第一个下级子元素
LastChild       返回当前元素的最后一个子元素
NextSibling    返回紧跟当前元素的后面一个元素
PreviousSibling  返紧邻当前元素的之前一个元素
ParentNode  返回父节点
NodeValue   返回元素值的读写(即使到了最后text对象也要用NodeValue读出来)

另外,在php中可以用echo动态声称一个xml然后返回,但必须加上头信息header('Content-type:text/xml')。














0 0
原创粉丝点击