HTML5第8次課堂筆記( 模擬form表單提交資料,xml的解析,jQuery的Ajax方法使用, mui的ajax)
HTML5第8次課堂筆記
1. 模擬form表單提交資料:(get方式)
<body>
<formmethod="get"action="DataTest7">
<inputtype="text"name="uname"value="yang"id="myname"><br/>
<inputtype="password"name="upass"value="123"id="mypass"><br/>
<inputtype="submit"value="login"><br/>
</
<script>
var oName=document.getElementById("myname").value;
var oPass=document.getElementById("mypass").value;
var xml=newXMLHttpRequest();
//建立請求
xml.open("GET","DataTest7?uname="+oName+"&upass="+oPass,true);
xml.onreadystatechange=function
{
if(xml.readyState==4)//響應回來,並不代表一定成功
{
if(xml.status==200)//請求成功
{
alert(xml.responseText);//返回響應正文
}
}
}
xml.send(null);
</script>
返回的資料:
2.
<body>
<formmethod="post"action="DataTest7">
<inputtype="text"name="uname"id="myname"value="fengjing"/><br/>
<inputtype="password"name="upass"id="mypass"value="123554"><br/>
<inputtype="submit"value="login"/>
</form>
<script>
var xhr=newXMLHttpRequest();
var uname=document.getElementById("myname").value;
var upass=document.getElementById("mypass").value;
xhr.open("POST","DataTest7",true);//構建請求
//xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//報頭可以隨便加
xhr.onreadystatechange=function(){
if(xhr.readyState==4)
{
if(xhr.status==200)
{
alert(xhr.responseText);//響應正文
}
}
};
xhr.send("uname="+uname+"&upass="+upass);
</script>
</body>
返回結果為null
可以看出通過ajax重新整理方式和表單提交方式的報頭方式不一樣,所以不能返回資料。
加上報頭,才可以返回正確的結果
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//報頭可以隨便加
3. 對於xml的解析:
<body>
<script>
var xhr=newXMLHttpRequest();
//建立請求
xhr.open("GET","DataTest4",true);
xhr.onreadystatechange=function()
{
if(xhr.readyState==4)//響應回來,並不代表一定成功
{
if(xhr.status==200)//請求成功
{
//返回報頭必須是application/xml或 text/xml會自動生成xml與伺服器端的互動
varonodes=xhr.responseXML.getElementsByTagName("title");//檢測到資料型別
//alert(onodes.length);
for(vari=0;i<onodes.length;i++)
{
alert(onodes[i].childNodes[0].nodeValue);//文字是第一個節點
}
}
}
}
xhr.send(null);
</script>
注意:xhr.responseXML代表XML DOM,前提是響應報頭Content-Type必須是text/xml或applicaion/xml
獲取title中的資料
var onodes=xhr.responseXML.getElementsByTagName("title");//檢測到資料型別
//alert(onodes.length);
for(vari=0;i<onodes.length;i++)
{
alert(onodes[i].childNodes[0].nodeValue);//文字是第一個節點
}
}
響應正文中返回的xml
4. .jQuery的Ajax方法使用
<body>
<scriptsrc="js/jquery-1.11.3.min.js"></script>
<script>
$.ajax({
url:"DataTest7",
cache:false,//防止快取
data:"uname=yang&upass=123",
//dataType:"xml",//返回xml
type:"GET",
success:function(res){//回撥
alert(res);
}
});
</script>
</body>
5. mui的ajax
http://dev.dcloud.net.cn/mui/ajax/