手机使用AJAX

测试一下手机浏览器对AJAX的支持:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//OMA//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
<title>title</title>
</head>
<body>
<div id="a"></div>
<div id='b'></div>
<input type="button" onclick="startXMLHttp();" value="发送GET" />
<div id="a1"></div>
<div id='b1'></div>
<input type="button" onclick="startXMLHttp1();" value="发送POST" />

<script type="text/javascript">
 //<![CDATA[
  var xmlHttp;
  function createXMLHttp()
  {
    if (window.XMLHttpRequest)
    {
      xmlHttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
      try
      {
        xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
      }
      catch(e)
      {
        try
        {
          xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
        }
        catch(e) {};
      }
    }
  }
  
  function startXMLHttp()
  {
    createXMLHttp();
    var sendStr = "name=博科&age=23";
    sendStr = encodeURI(sendStr);
  var t1 = document.createTextNode(sendStr);
    document.getElementById('a').appendChild(t1);
    xmlHttp.onreadystatechange = doSomething;
    xmlHttp.open('GET','ajaxtest.php?'+sendStr,true);
    xmlHttp.send(null);
  }
  
  function doSomething()
  {
    
    if (xmlHttp.readyState == 4)
    {
      if (xmlHttp.status == 200)
      {
    var t2 = document.createTextNode(xmlHttp.responseText);
        document.getElementById('b').appendChild(t2);
    //document.getElementById('b').innerHTML = xmlHttp.responseText;
      }
    }
  }
  
  function startXMLHttp1()
  {
    createXMLHttp();
    var sendStr = "name=博科&age=23";
    sendStr = encodeURI(sendStr);
  var t3 = document.createTextNode(sendStr);
    document.getElementById('a1').appendChild(t3);
    xmlHttp.onreadystatechange = doSomething1;
    xmlHttp.open('POST','ajaxtest1.php',true);
    xmlHttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    xmlHttp.send(sendStr);
  }
  
  function doSomething1()
  {
    if (xmlHttp.readyState == 4)
    {
      if (xmlHttp.status == 200)
      {
        var ret = eval('('+xmlHttp.responseText+')');
        var t4 = document.createTextNode('你的名字是'+ret.name+',年龄是'+ret.age); 
        document.getElementById('b1').appendChild(t4);
        //document.getElementById('b1').innerHTML = xmlHttp.responseText;
      }
    }
  }
 //]]>
</script>
</body>
</html>

由于是xhtml,如果服务器返回的数据里面有“&”,“<”等特殊字符,以及html标签等,就会提示解析错误,所以我们不能使用document.getElementById(‘b1′).innerHTML = xmlHttp.responseText了,这里需要注意。
推荐在服务器端将数据组装成JSON格式,然后在客户端使用createElement(),appendChild()等DOM方法生成所需的样式。

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>