前端之家收集整理的这篇文章主要介绍了
Ajax提交json格式数据,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
myAjax.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ajax提交数据</title>
</head>
<body>
<input id="username" type="text">
<input type="submit" value="提交" onclick="test()">
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/scripts/jquery-1.8.3.min.js"></script>
<script type="text/javascript"> function test(){ var my_username = $('#username').val(); var username = {'username': my_username}; var contextPath = '${pageContext.request.contextPath}'; alert(username.username); $.ajax({ type: "post",url: contextPath+"/myAjaxController",data: username,dataType: "json",success: function(msg){alert( msg );} }); } </script>
</body>
</html>
myAjaxController.java
package com.hongyewell.ajax;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
public class myAjaxController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
System.out.println(username);
String flag = "ok";
PrintWriter out = response.getWriter();
Gson gson = new Gson();
String flagJson = gson.toJson(flag);
out.write(flagJson);
}
}
servlet接收到数据
servlet返回给客户端的数据
原文链接:https://www.f2er.com/ajax/162705.html