1. 程式人生 > >Jquery+ajax+springMVC返回json的運用方法

Jquery+ajax+springMVC返回json的運用方法

JSP頁面:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>登入驗證</title>

  	<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
  	<script type="text/javascript">
  		$(function(){  			
  			//ajax驗證
  			$("#ajax1").click(function(){
  				alert(1);
  				$.post(
  					"ajax1.action",
  					function(result){
  						alert(2);
  						alert(result.ms);
  					}
  				);
  			});	
  		});
  	</script>
</head>

<body>
	<div id="con">
    	<div class="center"><h2>歡迎登入</h2></div>
    	<div>
    		<form action="login.action" method="post">
    		<table>
    			<tr>
    				<td>使用者名稱:</td>
    				<td colspan="3"><input type="text" name="name"/></td>
    				<td></td>
    			</tr>
    			<tr>
    				<td>密 碼:</td>
    				<td colspan="3"><input type="password" name="pwd"/></td>
    				<td></td>
    			</tr>
    			<tr>
    				<td>使用者名稱:</td>
    				<td><input type="text" name="code"/></td>
    				<td></td>
    			</tr>
    			<tr>
    				<td class="center">
    					<input type="submit" name="sub" value="登入"/>
    				</td>
    			</tr>
    			<tr>
    				<td>
    					<button id="ajax1">ajax測試1</button>
    				</td>
    			</tr>
    		</table>
    		</form>
    	</div>
    </div>
</body>
</html>
後臺控制類:
package com.login.control;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.login.bean.Users;
import com.login.service.UsersService;

/**
 * 使用者控制類
 * @author
 *
 */
@Controller
public class UsersControl {
	
	@RequestMapping(value="ajax1.action",method= RequestMethod.POST)
    	
@ResponseBody public Object ajax1(HttpServletRequest request){ System.out.println("進入控制類"); JSONObject json = new JSONObject(); String ms = "ajax測試1成功!哈哈!"; json.put("ms", ms); System.out.println("出控制類"); return json; } }
必須加這兩句才能返回json值
@RequestMapping(value="ajax1.action",method= RequestMethod.POST)
@ResponseBody