ホームページ  >  記事  >  ウェブフロントエンド  >  Jquery+ajax+springMVC が json を返す方法

Jquery+ajax+springMVC が json を返す方法

一个新手
一个新手オリジナル
2017-09-19 10:44:311335ブラウズ

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>
	<p id="con">
    	<p class="center"><h2>欢迎登录</h2></p>
    	<p>
    		<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>
    	</p>
    </p>
</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 値を返すには、これら 2 つの文を追加する必要があります

@RequestMapping(value="ajax1.action",method= RequestMethod.POST)
@ResponseBody

以上がJquery+ajax+springMVC が json を返す方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。