Ajax的工具類AjaxUtils,使用struts返回Json類型

bbw3 9年前發布 | 3K 次閱讀 Java

public class AjaxUtil {

/** 
 * ajax response method<br/> 
 * 如果出現異常,則返回錯誤代碼505 
 *  
 * @param response 
 * @param text 
 * ajax返回的內容 
 *  
 */  
public static void ajaxResponse(HttpServletResponse response, String text) {  
    try {  
        response.setContentType("text/html;charset=utf-8");  
        response.getWriter().write(text);  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  
}  

/** 
 * <pre> 
 * 注意:ajax請求必須攜帶:jsonnp請求callback 
 *  
 * eg: 
 * $.getJSON(path + "ajax/news/comment.go?newsId=" + newsId + "&content=" +content+ "&callback=?", function(data) { 
 *   alert(data['val']); 
 * }); 
 *  
 * </pre> 
 *  
 * @param response 
 * @param msg 
 */  
public static void jsonnpResponse(HttpServletResponse response,  
        String callback, String msg) {  
    try {  
        response.setContentType("text/html;charset=utf-8");  
        response.getWriter().write(callback + "(" + msg + ")");  
    } catch (IOException e) {  

    }  
}  

/** 
 * 異常操作,需要瀏覽器地址返回上一步 
 *  
 * @param response 
 * @param alertMsg 
 *            彈出提示信息 
 */  
public static void ajaxResponseRollBack(HttpServletResponse response,  
        String msg) {  
    try {  
        response.setContentType("text/html;charset=utf-8");  
        response.getWriter().write(  
                "<script type='text/javascript'>alert('" + msg  
                        + "');window.history.back();</script>");  
    } catch (IOException e) {  
        // LogConsoleUtil.write(Common.class, "ajaxResponseRollBack()",  
        // e.getMessage());  
    }  
}  

// ajaxJSON返回  
public static void ajaxJSONResponse(HttpServletResponse response,  
        String str, Object object) {  
    response.setContentType("text/json;charset=utf-8");  
    JSONObject json = new JSONObject();  
    json.put(str, object);  
    try {  
        response.getWriter().write(json.toString());  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  
}  

public static void ajaxResponseAlert(HttpServletResponse response,  
        String msg) {  
    try {  
        response.setContentType("text/html;charset=utf-8");  
        response.getWriter().write(  
                "<script type='text/javascript'>alert('" + msg  
                        + "');</script>");  
    } catch (IOException e) {  
        // LogConsoleUtil.write(Common.class, "ajaxResponseRollBack()",  
        // e.getMessage());  
    }  
}  

public static Integer StringToInteger(HttpServletRequest request,  
        String name) {  
    String obj = request.getParameter(name);  
    Integer result = -1;  
    if (obj != null) {  
        result = Integer.parseInt(obj);  
    }  
    return result;  
}  

} </pre>

 本文由用戶 bbw3 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!