1. 程式人生 > >原生js的Ajax提交json資料到後臺

原生js的Ajax提交json資料到後臺

原生ajax傳送json資料到後臺接收(將json轉換為name=tom&pwd=123格式的字串,簡單,不在本次測試內),需要做到幾點:

1,post方式傳送。

2、json物件必須轉換為json格式字串

3、(setQequestHeader,可以預設或者application/json;)

4、後臺接收,必須用request.getInputStream()方式。

SO:此種方式適合,前端傳送json資料,後臺接收後通過json解析,獲取每條資料

不過,jQuery可以輕鬆解決此問題,直接傳送json資料。(jQuery底層應該是先解析json成name=tom&pwd=123格式再提交後臺的,我的猜測)

------------------------------------------------------------------------------------------

<script type="text/javascript" >

function getXMLHttpRequest(){
var xmlhttp;
if (window.XMLHttpRequest)
{
//  IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執行程式碼
xmlhttp=new XMLHttpRequest();
}
else
{
// IE6, IE5 瀏覽器執行程式碼
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
window.onload=function()
{
var xmlhttp=getXMLHttpRequest();
var data={
"username":"湯姆",
"password":"123"
}
var stringData=JSON.stringify(data);


xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","${pageContext.request.contextPath}/AjaxDemo1",true);
//xmlhttp.setRequestHeader("text/plain;charset=UTF-8");//預設方式(可以傳送json格式字串)
//xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.setRequestHeader("Content-type","application/json;charset=UTF-8");//可以傳送json格式字串

//xmlhttp.send(data);//後臺無法接收
//傳送json資料,首先POST方式,再需要先格式化為json格式的字串傳送過去,後臺才能接收到,
//並且需要後臺通過request.getInputStream獲取資料,無法通過getInparamter方法獲取
xmlhttp.send(data);
}

</script>

後臺程式碼:

@WebServlet("/AjaxDemo1")
public class AjaxDemo1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");//null
String password = request.getParameter("password");//null
String contentType = request.getContentType();
//前端提交的資料是json格式的字串資料時,需要以下方式接收資料
ServletInputStream is = request.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line=null;
while((line=br.readLine())!=null){
System.out.println(line); //{"username":"湯姆","password":"123"}
}

System.out.println(contentType);
response.getWriter().print("username="+username+","+"password="+password);//null,null
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}


}