您的位置:首页 > Web前端 > JavaScript

原生js的Ajax提交json数据到后台

2017-09-26 10:57 585 查看
原生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);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐