原生ajax发送json数据到后台接收(将json转换为name=tom&pwd=123格式的字符串,简单,不在本次测试内),需要做到几点:
1,post方式发送。
2、json对象必须转换为json格式字符串
3、(setQequestHeader,可以默认或者application/json;)
4、后台接收,必须用request.getInputStream()方式。
SO:此种方式适合,前端发送json数据,后台接收后通过json解析,获取每条数据
不过,jQuery可以轻松解决此问题,直接发送json数据。(jQuery底层应该是先解析json成name=tom&pwd=123格式再提交后台的,我的猜测)
------------------------------------------------------------------------------------------
function getXMLHttpRequest(){后台代码:
@WebServlet("/AjaxDemo1")
public class AjaxDemo1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");//null
String password = request.getParameter("password");//null
String contentType = request.getContentType();
//前端提交的数据是json格式的字符串数据时,需要以下方式接收数据
ServletInputStream is = request.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line=null;
while((line=br.readLine())!=null){
System.out.println(line); //{"username":"汤姆","password":"123"}
}
System.out.println(contentType);
response.getWriter().print("username="+username+","+"password="+password);//null,null
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}