新手学ajax1

   学习的动力是最近想实现servlet向js传值,是html中的js,因为jsp是可以直接调用java 类的,在网上搜索了好久感觉ajax能帮我实现。

   以下代码可以实现js向服务器发出一 request服务器响应一个文本或者XML js接受并且向叶面输出,html页面很简单三个标签,俩链接,另外一个负责显示接受的数据,另外患有俩一个是txt文本,一个是XML格式的文件内涵choices标签

html

<!DOCTYPE html>
<html>
  <head>
    <title>readFromServer.html</title>
    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript" src="readFromServer.js"></script>
  </head>
  
  <body>

<a id="makeTextRequest" href="gAddress.txt">请求文本</a>
<a id="makeXMLRequest" href="us_states.xml">请求XML文件</a>
<div id="updateArea">&nbsp;</div>

  </body>
</html>
js
alert("start");
window.onload=initAll;
var xhr=false;//全局变量,在后面的真正使用时是接受的数据,这里bool型没什么用
function initAll(){
    document.getElementById("makeTextRequest").onclick=getNewFile;///该函数的返回值为false表示最后点击链接后不跳转页面,当然前提是返回语句以及返回语句之前的代码都是正确的
    document.getElementById("makeXMLRequest").onclick=getNewFile;
}

function getNewFile(){
    alert(this.href);
    makeRequest(this.href);//将所点击的链接的地址获取到
    return false;//不加载新页面 前提是这句语句以前的没有错误 否侧依然跳转
}
function makeRequest(url){
    if(window.XMLHttpRequest){//该对象存在表示当前浏览器是firefox,opera,safiar,IE7.0,IE8.0中的一个都有这个对象
        xhr=new XMLHttpRequest();    }
    else{
       if(window.ActiveXObject){//IE6.0,5.5中存在的是该对象
        
            try{
                xhr=new ActiveXObject("microsoft.XMLHTTP");
                }
            catch(e){}
        }
    }
    alert(xhr);
    if(xhr){//如果获得了xml对象
        alert("getxhr");
        xhr.onreadystatechange=showContents;
        xhr.open("GET", url,true);//请求的方法(get post head) 文件的地址 请求是否异步也就是我们是否会等到请求完成
        xhr.send(null);
    }
    else{
        document.getElementById("updateArea").innerHTML="抱歉,我不能创建XML请求";
    }
}
function showContents(){
    alert(xhr.readyState);
    if(xhr.readyState==4){//响应已经完全被接受
        alert(xhr.status);
        if(xhr.status==200){//200 表示请求的文件存在 404表示文件不存在
            
//alert(xhr.responseXML+".........."+xhr.responseXML.contentType);
            if(xhr.responseXML&&xhr.responseXML.contentType=="application/xml"){
                alert("XML");
                var outMsg=xhr.responseXML.getElementsByTagName("choices")[0].textContent;
            }
            else{
                alert("text");
                var outMsg=xhr.responseText;
            }
        }
        else{
            var outMsg="请求出现问题"+xhr.status;
        }
        document.getElementById("updateArea").innerHTML=outMsg;
    }
}
原文地址:https://www.cnblogs.com/xizhenghe/p/5460122.html