struts2 + jquery 的簡單ajax應用(備忘)

來源:互聯網
上載者:User
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>My JSP 'index.jsp' starting page</title><script type="text/javascript"src="http://code.jquery.com/jquery.min.js"></script><SCRIPT type="text/javascript">$(document).ready(function(){$("#send").click(function(){var url = 'ajax.action';   //要請求的actionvar params = {   //傳遞的參數username : $('#username').attr('value'),    password : $('#password').attr('value')};jQuery.post(url, params, myfun, 'json');   //jquery提供的ajax函數,myfun為回呼函數, 'json'為返回的資料類型});function myfun(data){var msg = $("#msg");msg.html(data.msg).fadeIn();setTimeout(function(){msg.fadeOut();},1000);}})</SCRIPT><style type="text/css">#msg{width:300px; height:50px; border:1px solid red; font-weight:900; display:none; text-align:center;}</style></head><body>username:<input type='text' name='username' id="username" value="" /><br>password:<input type='password' name="password" id="password" value="" /><br /><input type="button" value="submit" id="send"/><br/><div id="msg"></div></body></html>

使用json,大概是能直接讀取action中屬性的值而不用想servlet中的out.print( ... )

package com.ajax.action;import com.opensymphony.xwork2.ActionSupport;public class AjaxAction extends ActionSupport {private String username;//為減少牌面,自行添加get,set方法private String password;private String msg;public String execute() {if(username.equals("admin") && password.equals("admin")){msg = "hello, login successfully";}else{msg = "login fail";}return "success";}}

然後在配置xml檔案,主要是設定result的type為json,跟前面.post()中的dataType對應,還有就是要繼承json-default

<package name="ajax" namespace="/" extends="json-default"><action name="ajax" class="com.ajax.action.AjaxAction"><result type="json"></result></action></package>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.