jQuery.ajax 实现前后台数据传送

1、给出jsp文件。

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
%>


  
   
   
    My JSP 'index.jsp' starting page
  
  
   
   

2、给出my.js文件。

$(document).ready(function(){$("#btn").click(getData);});
function getData(){
   $.ajax({
        type: 'post',
        url: 'welcome.do',
        dataType: 'json',
        async:true,
        data:"id=huangyz&name=test&password=112358",
        success: function(responseText)
                  {
                   $("#panel").html(responseText[0]+"
"+responseText[1]+"
"+responseText[2]+"
");
                  } 
   })
  }

3、给出java类。

package com.huangyz.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class WelcomeYou extends Action {
    private IWelcome welcome;
    private String persons[] = { "huangyz", "xielong", "zhanghaifeng" };
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
              System.out.println(request.getParameter("id")+" "+request.getParameter("name")+" "+request.getParameter("password"));
               response.setContentType("text/plain;charset=utf-8");
        try {
            response.getWriter().write(toJsonArray(persons));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    } 
    public String toJsonArray(Object[] obj) {
        String doubleQuote = "/"";
        StringBuffer jsonArray = new StringBuffer();
        // 添加左【
        jsonArray.append("[");
        // 拼串开始
        for (int i = 0; i < obj.length; i++) {
            jsonArray.append(doubleQuote);
            jsonArray.append(obj[i]);
            jsonArray.append(doubleQuote);
            jsonArray.append(",");
        }
        // 去掉最后的,
        jsonArray.deleteCharAt(jsonArray.lastIndexOf(","));
        // 添加右】
        jsonArray.append("]");
        // 转化为字符串
        String json = jsonArray.toString();
        // 清空buffer
        jsonArray.delete(0, jsonArray.length());
        return json;
    }
}

4、struts配置部分不再给出,更多细节参考相关文档。

你可能感兴趣的:(jQuery.ajax 实现前后台数据传送)