jquery是一个优秀的js框架,自然对js原生的ajax进行了封装,封装后的ajax的操 作方法更简洁,功能更强大,与ajax操作相关的jquery方法有如下几种,
但开发中 经常使用的有三种:
1)$.get(url, [data], [callback], [type])
2)$.post(url, [data], [callback], [type])
其中:
url:代表请求的服务器端地址
data:代表请求服务器端的数据(可以是key=value形式也可以是json格式)
callback:表示服务器端成功响应所触发的函数(只有正常成功返回才执行)
type:表示服务器端返回的数据类型(jquery会根据指定的类型自动类型转换)
返回内容格式,xml, html, script, json, text, _default。
而我们通常使用json和text格式。
1)$.ajax( { option1:value1,option2:value2... } ); ---- 以后在掌握
常用的option有如下:
async:是否异步,默认是true代表异步
data:发送到服务器的参数,建议使用json格式
dataType:服务器端返回的数据类型,常用text和json
success:成功响应执行的函数,对应的类型是function类型
type:请求方式,POST/GET
url:请求服务器端地址
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~1)$.get(url, [data], [callback], [type])
JavaScript:
function fn1(){
//get异步访问
$.get(
"/WEB22/ajaxServlet2", //url地址
{"name":"张三","age":25}, //请求参数
function(data){ //执行成功后的回调函数
//{\"name\":\"tom\",\"age\":21}
alert(data.name);
},
"json"
);
}
注:
function(){} 方法是回调函数,
其方法加入参数值data(可以是任意参数,代表回调获取服务响应返回值,即就是,后台返回的字符串。)获取服务器响应的数据。
Servlet:
public class AjaxServlet2 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String age = request.getParameter("age");
System.out.println(name+" "+age);
//java代码只能返回一个json格式的字符串
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("{\"name\":\"汤姆\",\"age\":21}");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
servlet 只能够返回一个字符串,或者json的字符串给前台。jQuery的Ajax能够进行自动获取数据格式。
另:
jQuery方式提交中:
1、post提交中有中文的数据,不用进行编码解码。(jQuery自动编码一次)
2、get提交需要对数据进行编码解码。方式:
传统方式使用:request.setCharacterEncoding("UTF-8"); 解决数据乱码问题。