原生Ajax

原生Ajax

<span>输入账号 :</span>
<input id="name" name="name" οnkeyup="check()" type="text"> 
<span id="checkResult"></span>
  
<script>

第一步:jsp中设置全局变量
var xmlhttp;
function check(){
  var name = document.getElementById("name").value;
  var url = "http://how2j.cn/study/checkName.jsp?name="+name;

  第二步:实例化XMLHttpRequest
  xmlhttp =new XMLHttpRequest();

  第三步:设置响应函数checkResult,注意checkResult()错误!:后面不能加括号,加括号表示函数的结果
  xmlhttp.onreadystatechange=checkResult; 

  第四部:设置访问的页面
  xmlhttp.open("GET",url,true);   //设置访问的页面

  第五部:执行访问
  xmlhttp.send(null);  //执行访问
}
  
function checkResult(){
  第六部:编写响应函数
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    document.getElementById('checkResult').innerHTML=xmlhttp.responseText;
   
}
</script>

xmlhttp.send(null)
null表示没有参数,因为参数已经通过“GET" 方式,放在url里了。
只有在用"POST",并且需要发送参数的时候,才会使用到send。
类似这样:
    在提交之前需要设置请求头
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send("user="+username+"&password="+password)

xmlhttp.readyState 4 表示请求已完成
xmlhttp.status 200 表示响应成功
xmlhttp.responseText; 用于获取服务端传回来的文本
服务端传文本不要使用println(),可以使用print();

创建ajax对象有时候需要判定:
var xmlHttp;
if(window.ActiveXObject){
    xmlHttp = 
}else if(window.XMLHttpRequest){
    xmlhttp =new XMLHttpRequest();
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值