原生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);
}


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章