标签:ror response class html err 回调 包含 信息 post
1、ajax-get请求demo
1 <script> 2 document.getElementById("buttonname").onclik=function(){ 3 //发送AJAX查询请求 4 var request=new XMLHttpRequest(); 5 request.open("GET","xxxx.jsp?name="+document.getElementById("name").value + "&old="+document.getElementById("old").value); 6 request.send(); 7 request.onreadystatechange = funtion(){ 8 if(request.readState===4){ 9 if(request.status===200){ 10 document.getElementById("div").innetHTML= request.responseText; 11 }else{ 12 alert("请求错误"+request.status); 13 } 14 } 15 } 16 17 } 18 </script>
2、ajax-post请求demo
1 1 <script> 2 2 document.getElementById("buttonname").onclik=function(){ 3 3 //发送AJAX查询请求 4 4 var request=new XMLHttpRequest(); 5 5 request.open("POST","xxxx.jsp");
var data="name="+document.getElementById("name").value
+"&old="+document.getElementById("old").value;
requeat.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
6 6 request.send(data); 7 7 request.onreadystatechange = funtion(){ 8 8 if(request.readState===4){ 9 9 if(request.status===200){ 10 10 document.getElementById("div").innetHTML= request.responseText; 11 11 }else{ 12 12 alert("请求错误"+request.status); 13 13 } 14 14 } 15 15 } 16 16 17 17 } 18 18 </script>
3、ajax请求-返回JSON格式
{
"success":"true",
"msg":"text"
}
1 <script> 2 document.getElementById("buttonname").onclik=function(){ 3 //发送AJAX查询请求 4 var request=new XMLHttpRequest(); 5 request.open("GET","xxxx.jsp?name="+document.getElementById("name").value + "&old="+document.getElementById("old").value); 6 request.send(); 7 request.onreadystatechange = funtion(){ 8 if(request.readState===4){ 9 if(request.status===200){
var data=JSON.parse(request.responseText);
if(data.success){
document.getElementById("div").innetHTML= data.msg;
}else{
12 document.getElementById("div").innetHTML= data.msg;
13 }
10 }else{
12 alert("请求错误"+data.msg); 13 }
15 } 16 17 } 18 </script>
4、jQuery实现ajax
jQuery.ajax([settings])
type:类型,post或get,默认为get
url:发送请的地址
data:是一个对象,连同请求发送到服务器的数据
dataType:预期服务器返回的数据类型。如果不指定,jquery将自动根据HTTP包MIME信息来智能判断,一般我们采用json格式,可以设置为"json"
success:是一个方法,请求成功后的回调函数。传入返回的数据,以及包含成功代码的字符串
error:是一个方法,请求失败时调用此函数。传入XMLHttpRquest对象
例子:
$(document).ready(funtion(){
$("#name").click(funtion(){
$.ajax({
type:"GET",
url:"XXX.jsp?name="+$("#name").val(),
dataType:"json",
success:funtion(data){
if(data.success){
$("#name").html(data.msg);
}esle{
$("#name").html("发错了"+data.msg);
}
},
error.funtion(jqXHR){
alert("出错了"+jqXHR.status);
}
});
});
}
)
标签:ror response class html err 回调 包含 信息 post
原文地址:https://www.cnblogs.com/zhanglijun/p/11922229.html