java servlet+jquery+json学习小例子

引入JSON的jar包:

注意,如果包不全,页面请求servlet时,jquery ajax会返回error:function

弹出error occured!!!



HTML Code:


<%@ page language="java" pageEncoding="utf-8"%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
<head>  
<title>jquery ajax</title>  
<meta http-equiv="pragma" content="no-cache">  
<meta http-equiv="cache-control" content="no-cache">  
<meta http-equiv="expires" content="0">  
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
<meta http-equiv="description" content="This is my page">  
<script src="jquery/jquery-1.8.2.min.js" type="text/javascript"></script>  
<script language="javascript">  
    $(function(){   
        $('.sumbit').click(function(){   
        	var v = $('#account').val();
        	alert(v);
            if($('#account').val().length==0){   
                $('.hint').text("用户名不能位空").css({"background-color":"green"});    
            }else{   
                $.ajax({  
                		type:'get',
                    url:'jqueryAjax',   
                    data:{account:$('#account').val()},   
                    dataType:'json', //很重要!!!.预期服务器返回的数据类型 ,  
                    success:function(data){   
                        $.each(data.jsonArray,function(index){   
                            $.each(data.jsonArray[index],function(key,value){   
                                alert(key+":"+value)   
                            });   
                        });   
                           
                        $('body').append("<div>"+data.account+"</div>").css("color","red");   
                    },
                    error:function(){   
                        alert("error occured!!!");   
                    }   
                       
                });   
            }   
        });   
    });   
</script>  
</head>  
  
<body>  
<h3 align="center">jquery AjaX</h3>  
<hr>  
<label>请输入你的账户 :</label>  
<input id="account" name="account" type="text">  
<input class="sumbit" type="button" value="检测">  
<div class="hint"></div>  
</body>  
</html>

dataType:'json', //很重要!!!.预期服务器返回的数据类型 ,这句代码注释掉,也正常运行!

不知是否是servlet中写了这句代码的原因:

response.setContentType("application/x-json");(网上找下原因)

servlet Code:JqueryAjaxServlet.java

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 net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Author: YangT
 * Version: 1.0 
 * Create: 2013-3-13 上午10:34:58
 */
public class JqueryAjaxServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("JqueryAjaxServlet :  begin");
		
//		response.setContentType("text/html;charset=utf-8");
		String account = request.getParameter("account");
		System.out.println("account :" + account);

		JSONObject json = new JSONObject();
		JSONArray jsonArray = new JSONArray();

		JSONObject member = null;
		for (int i = 1; i < 3; i++) {
			member = new JSONObject();
			member.put("name", "yangting" + i);
			member.put("age", 22 + i);
			jsonArray.add(member);
		}
		json.put("jsonArray", jsonArray);
		json.put("account", account);

		//错误:response.setContentType("text/html;charset=utf-8");
                response.setContentType("application/x-json");
		PrintWriter pw = response.getWriter();
		pw.print(json.toString());

		System.out.println("json array :" + jsonArray.toString());
		System.out.println("json object :" + json.toString());
		System.out.println("JqueryAjaxServlet : end");
		
		pw.close();
		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		this.doGet(request, response);
	} 
	
}



web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  
    <servlet>
    	<servlet-name>JqueryAjaxServlet</servlet-name>
    	<servlet-class>JqueryAjaxServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>JqueryAjaxServlet</servlet-name>
    	<url-pattern>/jqueryAjax</url-pattern>
    </servlet-mapping>
    
</web-app>


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值