ajax学习中遇到的问题

来源:互联网 发布:mysql ubunty 编辑:程序博客网 时间:2024/05/17 06:42

经过好几天对Ajax的继续学习,在学习过程中遇到了不少问题。

1。 通过XMLHttpRequest.send(str)传递数据时,在后台接收不到。

  解决方法:传递前需要XMLHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

参数str需要是“name=value”的形式,然后在后台request.getParameter("name")这样就能把值取出。

2。send过去的数据直接声明的字符串如果是直接通过script声明的中文串传过去会出现乱码,从页面上取的没有问题。

未解决。

3。后台响应请求返回数据时一定要关闭流。

PrintWriter pw = response.getWriter();
pw.write("return");
pw.flush();
pw.close();

总结的一个ajax.js,代码如下

/**
 以ajax的同步交互方式与后台进行交互 06-12-03 cuiqh
**/ 
var xmlhttp,retValue;
function doWithAjax(url,postStr){  //postStr为"param1=value1&param2=value2"的形式
      if(window.ActiveXObject)
      {
         xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      else if(window.XMLHttpRequest)
   {
         xmlhttp=new XMLHttpRequest();
      }
      xmlhttp.open("POST",url,false); //以POST&同步方式传送数据
      xmlhttp.onreadystatechange=oncallback;
    xmlhttp.setrequestheader("cache-control","no-cache");
      xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      xmlhttp.send(postStr);
 }
 function oncallback()
 {
      if(xmlhttp.readyState==4)
      {
         if(xmlhttp.status==200)
         {
            retValue = xmlhttp.responseText;   
         }
      }
 }

 

 

 
原创粉丝点击