论坛首页 Web前端技术论坛

Ajax Form Post

浏览 9629 次
锁定老帖子 主题:Ajax Form Post
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-02-10  
Ajax Form Post
 
 
基于Ajax 技术我们可以页面无刷新提交,给用户带来了更好的体验。然而我们每次在后台提交的时候,却有不少的麻烦。
 
考虑一个简单的登陆/注册校验用户名是否存在的Case, 下面是Login.jsp
 
<form name="loginFrm" action=<c:urlvalue="/servlet/doLogin.htm"/>method="post">
 <input name="adminUser" type="hidden" value="Admin" />
 <p align="center">Login</p><br>
 UserName:
 <input type="text" name="userName" value="<c:outvalue="${viewState.userName}"/>">  
 <input type="button" value="Check"
 onclick="doCheckSubmit('<c:urlvalue='/servlet/doNameCheck.htm'/>')"/>
 <div id="checkResultDiv" ></div>
 <br>
 Password:<input type="password" name="password">
 <br>
 <p>
 <input type="submit" value="Submit" name="btnLogin" />
 <input type="reset" value="Reset" name="btnReset" />
 </p>
</form>      
 
如果我们用Ajax提交的话,如下
function doCheckSubmit( actionUrl )
{
   var ajaxObj = new AjaxObject();
   actionUrl = actionUrl + "?userName=" + ocument.loginFrm.userName.value;
   var res = ajaxObj.httpPost(actionUrl);
   
   document.getElementById('checkResultDiv').innerHTML = '<B>' + res + '</B>';
}
 
ActionUrl中的Form对象,即参数必须我们手工每次去构造,如果参数很多的话,会比较麻烦。
 
 
而在服务器端,我们是如下处理的:
/**
     * doNameCheckOld  on user submit
     */
    public ModelAndView doNameCheckOld(HttpServletRequest req, HttpServletResponse res, UserInfo info ) throws Exception {
                                // TODO Auto-generated method stub
               
                  // 注意:此时info的值为空   
                String userName = req.getParameter("userName");
               
                if ( userName != null && userName.trim().toUpperCase().equals("USERNAME") )
                {
                                res.getWriter().write(userName + " is already been used.");
                }
                else
                {
                                res.getWriter().write("userName is not been used.");
                }
               
               return null;
}
 
 
此时info的值为空,因为我们使用Ajax提交,Ajax只是局部提交,所以我们后台无法取到Form的参数,只有靠传递参数来获取。String userName = req.getParameter("userName"); 所以此时cmd Model 完全无法发挥作用,当传递参数很多的时候难免会复杂容易出错。
               
 
解决方案:
Ajax 提供Form提交帮助函数,此时服务器端的cmd Model也可以用了。
//-------------------------------------------------------
// Date   : 2007/01/25
// Desc   : http Form PostForm
//                   include type : hidden,text,select, checkbox,radio,file
//                   none-include : button,submit,reset,image
// Params : frmID: Form's ID or Name
//-------------------------------------------------------
function httpPostForm(frmID, URL, data, contentType) {
 
       //alert(URL);
      URL += ('?' + getFormQueryString(frmID));
        //alert(URL);
     
    this.init(URL,data,contentType);  
 
    return trim(this.httpObj.responseText);  
}
 
//-------------------------------------------------------
// Date   : 2007/01/25
// Desc   : Get all the from object
//                   include type : hidden,text,select, checkbox,radio,file
//                   none-include : button,submit,reset,image
// Params : frmID: Form's ID or Name
//-------------------------------------------------------
function getFormQueryString( frmID )
{
       var i,queryString = "", and = "";
       var item; // for each form's object
       var itemValue;// store each form object's value
      
       for( i=0;i<frmID.length;i++ )
       {
              item = frmID[i];// get form's each object
             
              if ( item.name!='' )
              {
                     if ( item.type == 'select-one' )
                     {
                            itemValue = item.options[item.selectedIndex].value;
                     }
                     else if ( item.type=='checkbox' || item.type=='radio')
                     {
                            if ( item.checked == false )
                            {
                                   continue;   
                            }
                            itemValue = item.value;
                     }
else if ( item.type == 'button' || item.type == 'submit' ||
tem.type == 'reset' || item.type == 'image')
                     {// ignore this type
                            continue;
                     }
                     else
                     {
                            itemValue = item.value;
                     }
                    
                     itemValue = encodeURIComponent(itemValue);
                     queryString += and + item.name + '=' + itemValue;
                     and="&";
              }
       }
             
       return queryString;
}
 
 
JSP
 
function doCheckSubmit( actionUrl )
{
       var ajaxObj = new AjaxObject();
       //actionUrl = actionUrl + "?userName=" + document.loginFrm.userName.value;
       var res = ajaxObj.httpPostForm(loginFrm,actionUrl);
   
           document.getElementById('checkResultDiv').innerHTML = '<B>' + res + '</B>';
}
 
 
-----------------------------------------------------------------------------------------后台
/**
     * do Login on user submit
     */
    public ModelAndView doNameCheck(HttpServletRequest req, HttpServletResponse res,
                                UserInfo info ) throws Exception {
                                // TODO Auto-generated method stub
                               
                //String userName = req.getParameter("userName");
               
                if ( info != null )
                {
                       _logger.info(info.toString());
                }
               
                if ( info.getUserName() != null && info.getUserName().trim().toUpperCase().equals("USERNAME") )
                {
                                res.getWriter().write(info.getUserName() + " is already been used.");
                }
                else
                {
                                res.getWriter().write("userName is not been used.");
                }
               
               return null;
}
   发表时间:2007-02-13  
当URL上存在parameter对应的value中包含诸如:'%'或';'等特殊字符时,你就挂了:)
0 请登录后投票
   发表时间:2007-02-13  
另外,你对UI组件的type类型分析不够全面。例如还有:.disabled的控件或.style.display == 'none'的,即你拿不到的或你不愿意拿到的也要做控制~
0 请登录后投票
   发表时间:2007-02-13  
j2eeqk 写道
另外,你对UI组件的type类型分析不够全面。例如还有:.disabled的控件或.style.display == 'none'的,即你拿不到的或你不愿意拿到的也要做控制~
有道理,多谢!
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics