微信小程序-ajax发post请求 json 和 application/x-www-form-urlencoded

前端向后端传输数据时,如果是get传输,直接传在url后;

 url: this.data.host + '/student/get?teacherId=' + teacherId + '&studentId=' + studentId,
 method: 'get',

如果是post传输,则在请求体body中传输。

url: this.data.host + '/student/getList',
method: 'get',
data:{
    "teacherId ":this.data.teacherId ,
    "teacherId ":this.data.teacherId ,
}

put提交方式:

url: that.data.host + '/student/update',
method: 'PUT',
data: {
          teacherId: teacherId,
},

delete提交方式:

 wx.request({
      url: this.data.host + '/student/delete?teacherId=' + teacherId + '&studentId=' + studentId,
      method: 'DELETE',
      success: function(res) {
            //成功执行事件
        } 
      }
    })
  • 对于 POST 方法且 header['content-type'] 为 application/json 的数据,会对数据进行 JSON 序列化
  • 对于 POST 方法且 header['content-type'] 为 application/x-www-form-urlencoded 的数据,会将数据转换成 query string

=================================================================================

body中的数据格式又有两种,一种是  json  数据格式,另一种是 字符串。具体要用哪种格式取决于后端入参的格式。

如果后端接收json数据类型,post 的 headers 需要设置;,传给后端的数据就形如  { "teacherId","6596a4b268634e2baf11a569a8fa4b77"} 

header: {
          'content-type': 'application/json' // 默认值
        },

如果后端接收的是(表单)字符串类型,post 的 headers 需设置  { ‘content-type’: ’application/x-www-form-urlencoded’ },

,传输给后端的数据就形如   'name=张三&age=22';

ajax默认数据格式为json,所以:

1.当后端需要接收json格式的数据时,post请求头不需要设置请求头,数据格式也不需要我们去转换(若数据已经是json);

扫描二维码关注公众号,回复: 11145126 查看本文章

2.当后端需要接收字符串格式的数据时,我们需要给post请求头设置

header: {
          //'content-type': 'application/json' // 默认值
          'content-type': 'application/x-www-form-urlencoded'
        },

接收 json格式的数据格式

ajax请求中content-type:application/json代表参数以json字符串传递给后台,controller接收需要@RequestBody 接收参数

例如:@RequestBody Map<String, Object> map,也可以使用类接收@RequestBody User user

接收form表单 字符串格式的数据

ajax请求中content-type:application/x-www-form-urlencoded代表参数以键值对传递给后台,controller接收可以单个参数接收,例如:@RequestParam("param") String param;也可以用类接收User user,

参考文章:

https://www.cnblogs.com/edwardwzw/p/11694903.html;

https://www.jianshu.com/p/b0d6504c7ccb;

❤如果文章对您有所帮助,就在文章的右上角或者文章的末尾点个赞吧!(づ ̄ 3 ̄)づ

❤如果喜欢大白兔分享的文章,就给大白兔点个关注吧!(๑′ᴗ‵๑)づ╭❤~

❤对文章有任何问题欢迎小伙伴们下方留言或者入群探讨【群号:708072830】

❤鉴于个人经验有限,所有观点及技术研点,如有异议,请直接回复讨论(请勿发表攻击言论)。

原创文章 114 获赞 270 访问量 46万+

猜你喜欢

转载自blog.csdn.net/weixin_43970743/article/details/104847146