萬盛學電腦網

 萬盛學電腦網 >> 腳本專題 >> javascript >> js調用AJAX時Get和post的亂碼

js調用AJAX時Get和post的亂碼

 在使用"get"時,抓取的頁面最後加上編碼類型 

 代碼如下: <%  服務器端:servletactioncontext.getresponse().setcharacterencoding("utf-8");  客戶端 網頁特效p/jsp.html target=_blank >jsp教程: <%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%>  response.expires = -9999  response.addheader "pragma","no-cache"  response.addheader "cache-ctrol","no-cache"  response.addheader "content-type","text/html; charset=gb2312"'這是重點,否則會出現亂碼  response.write "中文漢字"%>    2、在使用post時用vbscript解決了編碼問題:  源碼如下:   代碼如下: <script language="vbscript">  function urlencoding(vstrin)  strreturn = ""  for i = 1 to len(vstrin)  thischr = mid(vstrin,i,1)  if abs(asc(thischr)) < &hff then  strreturn = strreturn & thischr  else  innercode = asc(thischr)  if innercode < 0 then  innercode = innercode + &h10000  end if  hight8 = (innercode and &hff00) &hff  low8 = innercode and &hff  strreturn = strreturn & "%" & hex(hight8) & "%" & hex(low8)  end if  next  urlencoding = strreturn  end function  function bytes2bstr(vin)  strreturn = ""  for i = 1 to lenb(vin)  thischarcode = ascb(midb(vin,i,1))  if thischarcode < &h80 then  strreturn = strreturn & chr(thischarcode)  else  nextcharcode = ascb(midb(vin,i+1,1))  strreturn = strreturn & chr(clng(thischarcode) * &h100 + cint(nextcharcode))  i = i + 1  end if  next  bytes2bstr = strreturn  end function  </script>    下面是使用vbscript函數:   代碼如下: <script language=網頁特效>  /**  * 初始化一個xmlhttp對象  */  function initajax()  {  var ajax=false;  try {  ajax = new activexobject("msxml2.xmlhttp");  } catch (e) {  try {  ajax = new activexobject("microsoft.xmlhttp");  } catch (e) {  ajax = false;  }  }  if (!ajax && typeof xmlhttprequest!='undefined') {  ajax = new xmlhttprequest();  }  return ajax;  }  function saveuserinfo()  {  var msg = document.getelementbyid("msg");  var f = document.user_info;  var username = f.user_name.value;  var userage = f.user_age.value;  var usersex = f.user_sex.value;  var url = "save.asp教程";  var poststr = urlencoding("user_name="+ username +"&user_age="+ userage +"&user_sex="+ usersex);//post時采用編碼傳遞  var ajax = initajax();  ajax.open("post", url, true);  ajax.setrequestheader("content-type","application/x-www-form-urlencoded");  ajax.send(poststr);  ajax.onreadystatechange = function() {  if (ajax.readystate == 4 && ajax.status == 200) {  msg.innerhtml = bytes2bstr(ajax.responsebody); //獲取時解碼  }  }  }  </script>  <form name="user_info">  姓名:<textarea name="user_name" /></textarea><br />  年齡:<input type="text" name="user_age" /><br />  性別:<input type="text" name="user_sex" /><br />  <input type="button" value="提交表單" onclick="saveuserinfo()">  </form>  <div id="msg"></div>  成功     
copyright © 萬盛學電腦網 all rights reserved