AJAX非同期リクエスト受信の3つの実装方式
2551 ワード
方式一:JS実現AJAX例
方式二:JQ標準実現AJAX例
方式3:JQ簡略実現AJAX例
window.onload = function () {
document.getElementById("un").onblur = function () {
var xmlhttp;
if (window.XMLHttpRequest != null) {
xmlhttp = new XMLHttpRequest();
}else {
xmlhttp = new ActiveXObject();
}
xmlhttp.open("GET","${pageContext.servletContext.contextPath}/ajax?sName="+document.getElementById("un").value,true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var div = document.getElementById("div");
var v = xmlhttp.responseText;
var vp = JSON.parse(v);
if (vp.userExist){
div.style.color="#ff0000";
div.innerText = vp.msg;
}else {
div.style.color="#00ff00";
div.innerText = vp.msg;
}
}
}
}
}
方式二:JQ標準実現AJAX例
$(function () {
$("#un").blur(function () {
$.ajax({
url:"${pageContext.servletContext.contextPath}/ajax",
type:"POST",
data:{"sName":$("#un").val()},
success:function (data) {
if (data.userExist) {
$("#div").css("color","red").text(data.msg);
} else {
$("#div").css("color","green").text(data.msg);
}
},
dataType:"json"
});
});
});
方式3:JQ簡略実現AJAX例
$(function () {
$("#un").blur(function () {
$.post("${pageContext.servletContext.contextPath}/ajax",{"sName":$("#un").val()},function (data) {
if (data.userExist) {
$("#div").css("color","red").text(data.msg);
} else {
$("#div").css("color","green").text(data.msg);
}
},"json");
});
});