1.摘要
刚开始学习jquery的时候,按照书上的例子发送POST请求始终失败,而发送GET请求却能够成功,在后台(java侧)使用@RequestBody将请求转换成json格式始终失败,查看了各种帖子始终不成功 。后来发现是页面转换json有问题,特将过程整理至此,希望对读者有益。
2. 通过页面发送POST请求
其代码对应如下
<!DOCTYPE html>
<html>
<head>
<script src="../src/js/lib/jquery.js" type="text/javascript"></script>
</head>
<style>
.inputDemo01{
width:800px;
height:20px;
}
.inputDemo00{
width:800px;
height:20px;
}
.inputDemo02{
width:800px;
height:400px;
};
</style>
<script>
var jst = {"name":"zhangsan","age":"99"};
$(function(){
document.getElementById("span001").style.color="red";
$('#inputDemo02').attr("disabled",true);
$("#inputSubmit").click(function(){
$.ajax({
url:$("#inputDemo00").val(),
data:JSON.stringify(JSON.parse($("#inputDemo01").val())),
type:"POST",
contentType:'application/json;charset=UTF-8',
cache:"false",
dataType:"json",
success:function(data){
var res = JSON.stringify(data);
$("#inputDemo02").val(res);
},
error:function(data){
alert(data);
}
});
});
})
</script>
<body>
<table>
<tr>
<td><span id="span000">*</span>url</td>
<td><input class="inputDemo00" id="inputDemo00" value="http://localhost:8080/ccgms/xmlhttptest01.do"/></td>
</tr>
<tr>
<td><span id="span001">*</span>Content</td>
<td><input class="inputDemo01" id="inputDemo01" value='{"name":"zhangsan","age":"99"}'/></td>
</tr>
<tr>
<td>result</td>
<td><input class="inputDemo02" id="inputDemo02"/></td>
</tr>
<tr>
<td> <input id="inputSubmit" align="right" type="button" value="send"></td>
</tr>
</table>
</body>
</html>
其中导致出错的是上述data的填写。读取用户输入到输入框中的内容是,{ 和 “ 都是经过转译的,即\",这点可以通过在IE上由F12抓取消息包看到。所以要先将其通过JSON.parse函数转换成json格式,而后再由JSON.stringify转换成字符串格式。如果直接在页面中构造data,则不需要JSON.parse转换。
更多推荐
使用 $.ajax 发送 post 请求
发布评论