使用 $.ajax 发送 post 请求

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转换。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值