标准模板 var util = require('../../utils/util.js') wx.request({ url: 'https://URL', data: {}, method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT // header: {}, // 设置请求的 header success: function(res){ // success }, fail: function() { // fail }, complete: function() { // complete } }) 注意几点: 1.method 必须参数必须是大写的 2.GET方式请求时,data:传输json类型,但是在POST 请求方式中,data如果直接传json数据,服务器会接受不到数据
所以在post请求需要特殊处理一下
wx.request({
url: 'http://kuzoutianya.com/xxxx',
data: Util.json2Form({
name:"酷走天涯",
text:"你好"
}),
method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: {"Content-Type": "application/x-www-form-urlencoded"}, // 设置请求的 header
success: function(res){
console.log(res);
},
fail: function() {
// fail
},
complete: function() {
// complete
}
})
}
特殊处理1: >header: {"Content-Type": "application/x-www-form-urlencoded"} 特殊处理2: >data: Util.json2Form({ name:"酷走天涯", text:"你好" }) 上面的Util.json2Form 的作用是将json数据进行网络编码拼接 结果如下 name=%E5%BE%90%E6%9D%B0&text=%E4%BD%A0%E5%A5%BD
实现方式
util.js 文件
>function json2Form(json) {
var str = [];
for(var p in json){
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
}
console.log(str.join("&"));
return str.join("&");
}
module.exports = {
json2Form:json2Form,
}
encodeURIComponent函数:可把字符串作为URI 组件进行编码