使用jQuery的方法,实现ajax访问服务器的2种方式
1.$.ajax(json对象)
$.ajax( {
type: "POST/GET",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
// 业务逻辑 msg是服务器传来的数据
}
dataType:'json'
} );
2.$.get/post(url,data,函数)
$.get(
"url",
{ name: "John", time: "2pm" },//参数以json方式传送给服务器
function(data){业务逻辑},//msg是服务器传来的参数.
'json' //回调函数的data是json对象,默认为text
) ;
-案例,检测帐号是否存在
- html代码
//不在html中写事件,全部交给js处理
<input type="text" id="username">
<span id="checkRet"></span>
- js代码
$(
function(){
$("#username").change(function(){
$.get(
"/MyAjax/ajax_check",
{username:$("#username").val()},
function(data){
$(#"checkRet").text(data.msg);//修改span的文本内容
//修改文本内容样式
if(data.success){$(checkRet).css("color","blue");}
else{$(#"checkRet").css("color","red");}
},
"json");
})})
- action代码
public String check() throws Exception {
//username是ajax传递过来的参数
//usernamelist是数据库传来的数据
Map map=new HashMap<>();
if(!usernameList.contains(username)) {
map.put("success", true);
map.put("msg", "帐号可以使用");
}else {
map.put("success", false);
map.put("msg", "帐号已经存在");
}
//JSON是fastjson.jar的类,作用是将list或对象/对象变成json形式的字符串.(jQuery.get会eval("("+字符串+")")返回一个json对象放在回调函数中作为形参);
this.print(JSON.toJSONString(map));
return this.NONE;
}
//向ajax输出
public void print(String str) throws Exception {
ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
ServletActionContext.getResponse().getWriter().print(str);
}