java - 如何从struts操作类返回对ajax的多个响应?

标签 java jquery ajax jsp struts-1

我需要从 struts(1.3.10) 操作类返回对 ajax 的响应。 我使用 PrintWriter 类将响应返回给客户端(浏览器)。它有时有效,但有时,它会在 jsp 页面中显示响应。

这是我的 jsp 和 ajax 函数:

<html:submit property="" styleClass="btn btn-success" onclick="doChangePassword()">Ok</html:submit>

 <script type="text/javascript">
        function doChangePassword(){
            //get the form values
            var oldPassword = $('#oldPassword').val();
            var newPassword = $('#newPassword').val();
            var confirmPassword = $('#confirmPassword').val();
            //                alert(customerName+" "+imeiNo+" "+targetName+" "+simNo+" "+duedate+" "+remark);

            $.ajax({
                type: "POST",
                url: "/GPS-VTS/change_account_password.do",
                data: "oldpassword="+oldPassword+"&newpassword="+newPassword+"&confirmpassword="+confirmPassword,
                dateType: "string",
                success: function(response){
                                                            alert(response);
                    var result = $.trim(response);
                    //                                                alert(result);
                    if(result === "oldPassword")
                    {

                            //  Example.show("Hello world callback");
                            alert("Please provide valid entries for Old Password field.");
                            $('#oldPassword').val("");
                        //alert('Product sold successfully.');


                    }
                    else if(result === "newPasswordEmpty"){
                        alert("Please provide valid entries for New Password field.");
                    }
                    else if(result === "newPassword")
                    {
                            alert("Please provide valid entries for New or Confirm Password fields.");
                            $('#newPassword').val("");
                            $('#confirmPassword').val(""); 
                    }else if(result === "success")
                    {
                            alert("Password Successfully Changed.");
                            $('#oldPassword').val("");
                            $('#newPassword').val("");
                            $('#confirmPassword').val("");    

                    }
                },
                error: function(e){
                    alert('Error :'+e);
                }

            });
        }
    </script>

这是我的操作类(account_password_action.java):

public class account_password_action extends org.apache.struts.action.Action {

/* forward name="success" path="" */
private static final String SUCCESS = "success";
private static final String FAILURE = "failure";
private long account_id;
private String encrypted_password = new String();
private String account_name = new String();
private String account_password = new String();

/**
 * This is the action called from the Struts framework.
 *
 * @param mapping The ActionMapping used to select this instance.
 * @param form The optional ActionForm bean for this request.
 * @param request The HTTP Request we are processing.
 * @param response The HTTP Response we are processing.
 * @throws java.lang.Exception
 * @return
 */
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {




    /*Get Session Value*/
    String acc_name = request.getSession().getAttribute("login_name").toString();

    /*Create Session Factory Object*/
    SessionFactory factory = new Configuration().configure().buildSessionFactory();
    Session session = factory.openSession();

    Transaction t = session.beginTransaction();

    /*Extract user data from Bean class -> account_bean.java*/
    account_password_bean fromBean = (account_password_bean) form;
    String old_password = fromBean.getOldpassword();

    /*get encrypted password from database*/
    Query enc_password = session.createQuery("from account_dao where name=?");
    enc_password.setString(0, acc_name);
    List list = enc_password.list();
    for (Iterator iterator = list.iterator(); iterator.hasNext();) {
        account_dao account = (account_dao) iterator.next();
        account_id = account.getId();
        account_name = account.getName();
        encrypted_password = account.getPassword();
    }

    /*Decrypt the password using AES algorithm*/
    account_password = AESencrp.decrypt(encrypted_password.toString().trim());

    if (!old_password.equals(account_password)) {
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("cache-control", "no-cache");
        //out.print("oldPassword");
        out.write("oldPassword");
        out.flush();
        return null;
    }
     else if(fromBean.getNewpassword().equals("") || fromBean.getNewpassword() == null)
    {
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("cache-control", "no-cache");
        //out.print("newPasswordEmpty");
        out.write("newPasswordEmpty");
        out.flush();
        return null;
    } 
    else if (fromBean.getNewpassword().equals(fromBean.getConfirmpassword())) {
        String new_password = fromBean.getNewpassword();
        String new_enc_password = AESencrp.encrypt(new_password.toString().trim());
        Query update_query = session.createQuery("update account_dao set password = :newPassword" + " where id = :Id");
        update_query.setParameter("newPassword", new_enc_password);
        update_query.setParameter("Id", account_id);
        int update_status = update_query.executeUpdate();
        t.commit();
    } 
    else {
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("cache-control", "no-cache");
        //out.print("newPassword");
        out.write("newPassword");
        out.flush();
        return null;
    }


    PrintWriter out = response.getWriter();
    response.setContentType("text/html;charset=utf-8");
    response.setHeader("cache-control", "no-cache");
    out.write("success");
    out.flush();
    return null;
    //return mapping.findForward(SUCCESS);

}

}

这是我在 Chrome 浏览器中的输出:

enter image description here enter image description here

火狐浏览器:

enter image description here

有时它会在警报框中显示正确的输出:

enter image description here enter image description here

大家好,请帮助我如何查看每次在警报框中显示的回复。 我能做些什么?什么问题?我该如何解决它?浏览器版本有问题吗?

请大家帮帮我......

提前致谢。

最佳答案

在您的 ajax 调用中,提供附加参数 async : false

   $.ajax({
                    type: "POST",
                    url: "/GPS-VTS/change_account_password.do",
                    async: false,
                    data: "oldpassword="+oldPassword+"&newpassword="+newPassword+"&confirmpassword="+confirmPassword,
                    dateType: "string",
                    success: function(response){
                     .....

           }

引用this 了解有关 ajax 中同步和异步调用的更多信息。
请参阅this 了解有关 ajax 调用的更多信息。

关于java - 如何从struts操作类返回对ajax的多个响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20756247/

相关文章:

javascript - Jquery 如果没有 -

php - 将数据推送到页面而不定期检查它?

Java : Proto parser library

java - 是否有 Java 等价于 JavaScript var a = b || C

php - http请求AJAX

javascript - 我需要从服务器发送日期数据,然后使用 Google Charts 中使用的 google.visualization.datatable 中的日期过滤元素

javascript - jQuery .each() 和 ajax 获取大小

java - 编译项目中包含哪些 Maven 依赖范围?

java - 将多个 Mono<List<Item>> 合并为一个

javascript - jQuery 精简版/AngularJS : How to add a class to a single child of an element?