ajax实现异步交互

来源:互联网 发布:嘉实红利优化股票基金 编辑:程序博客网 时间:2024/05/18 03:17

 

        今天用ajax实现了页面无刷新和后台交互并更新页面数据的功能,现在整理出来和大家分享,希望大家补充。

1、javascript代码,实现ajax与后台交互,在前台页面调用receive方法;

<script language="javascript" type="text/javascript">                 var xmlHttpRequest;  //定义一个变量用于存放XMLHttpRequest对象        //定义一个用于创建XMLHttpRequest对象的函数        function createXMLHttpRequest()        {           if(window.ActiveXObject)           {              //IE浏览器的创建方式              xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");           }else if(windew.XMLHttpRequest)           {              //Netscape浏览器中的创建方式              xmlHttpRequest = new XMLHttpRequest();           }        }        //响应HTTP请求状态变化的函数        function httpStateChange()        {           //判断异步调用是否完成           if(xmlHttpRequest.readyState == 4)           {              //判断异步调用是否成功,如果成功开始局部更新数据              if(xmlHttpRequest.status == 200||xmlHttpRequest.status == 0)              {             var flag = xmlHttpRequest.responseText;             alert(flag);              }else              {                  //如果异步调用未成功,弹出警告框,并显示出错信息                   alert("异步调用出错/n返回的HTTP状态码为:"+xmlHttpRequest.status + "/n返回的HTTP状态信息为:" + xmlHttpRequest.statusText);              }            }         }            //异步调用服务器段数据         function receive(id)         {                               //创建XMLHttpRequest对象            createXMLHttpRequest();            var url = "xxx.do?method=xxx&parameter="+id;            if(xmlHttpRequest!=null)            {               //创建HTTP请求               xmlHttpRequest.open("get",url,true);               //设置HTTP请求状态变化的函数               xmlHttpRequest.onreadystatechange = httpStateChange;               //发送请求               xmlHttpRequest.send(null);             }          }
     //edit 20140809 用jQuery  <pre name="code" class="javascript">$.ajax({ //一个Ajax过程 type: "post", url : url,  dataType:'json',<pre name="code" class="javascript">        success: function(json){    for(var i = 0; i < json.length; i++){  //通过for循环获取json里面的数据alert(json[i].flag);alert(json[i].notionString);            }        } 
}); 
</script>

2、xmlHttpRequest.open("get",url,true) ;  通过url链接到后台,前台可以获取到flag参数,如上httpStateChange方法,alert(flag);

    update 20140926 返回json数组

         public void xxx(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception {<pre code_snippet_id="446311" snippet_file_name="blog_20140809_5_4894517" class="html" name="code"><span style="white-space:pre"></span>String flag = "返回到前台的数据";String data = "[{\"flag\":\"" + flag + "\",\"notionString\":\"" + notionString + "\"}]";//拼接json格式字符串
                //设置编码格式 
                response.setContentType("text/html");response.setCharacterEncoding("UTF-8");PrintWriter out = response.getWriter();       out.write(<span style="font-family:Arial, Helvetica, sans-serif;">data</span>); 
        }

 

 

原创粉丝点击