首先建立一个web工程:

在WebRoot下建立一个文本文档ajaxtest.txt,在里面写上一点内容:hello ajax

hello world

在index.jsp的head中写入如下代码:

function getContent(){

var xmlhttpRequest=new XMLHttpRequest();

xmlhttpRequest.onreadystatechange=function(){

if (xmlhttpRequest.readyState==4 && xmlhttpRequest.status==200){

document.getElementById("content").value=xmlhttpRequest.responseText;

}

}

xmlhttpRequest.open("GET","/txt/ajaxtest.txt",true);

xmlhttpRequest.send();

}

其中readyState=4表示Http响应已经完全接收,status是状态码,200表示成功,

当两个条件都满足时,就可以接收服务器返回的数据。

没有使用XMLHttpRequest()去请求是不会触发这个函数的,请求的代码是:xmlhttpRequest.open("GET","/ajaxtest.txt",true);

xmlhttpRequest.send();

在body中写上如下代码:

当你点击button的时候就会得到你在文本文档中写的内容。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐