var querystring = require('querystring')
var https = require('https')
var post_data = querystring.stringify({
"name":"BOb",
"age":30,
"job":"teacher"
})
var post_req = https.request(post_opt,function(res){
//some code here
})
post_req.write(post_data)
post_req.end()
然而官方api要求发送的数据是这样的:
{
"action_name": "QR_LIMIT_SCENE",
"action_info": {
"scene": {
"scene_id": 1000
}
}
}
也就是说,调用了querystring.stringify方法之后,变成了action_name=QR_LIMIT_SCENE&action_info=。
//原生js实现Ajaxfunction ajax() {
var ajaxData = {
type: arguments[0].type || "GET",//提交方式,默认get
url: arguments[0].url || "",//路径
async: arguments[0].async || "true",//是否异步,默认异步
data: arguments[0].data || null,//参数
dataType: arguments[0].dataType || "text",//类型
contentType: arguments[0].contentType || "application/x-www-form-urlencoded",
beforeSend: arguments[0].beforeSend || function() {},
success: arguments[0].success || function() {},
error: arguments[0].error || function() {}
}
ajaxData.beforeSend()//默认执行before方法
var xhr = createxmlHttpRequest()//创建request对象
xhr.responseType = ajaxData.dataType
xhr.open(ajaxData.type, ajaxData.url, ajaxData.async)
xhr.setRequestHeader("Content-Type", ajaxData.contentType)
xhr.send(convertData(ajaxData.data))
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
ajaxData.success(xhr.response)
} else {
ajaxData.error()
}
}
}
}
function createxmlHttpRequest() {
if(window.ActiveXObject) {//判断IE
return new ActiveXObject("Microsoft.XMLHTTP")
} else if(window.XMLHttpRequest) {
return new XMLHttpRequest()
}
}
function convertData(data) {
if(typeof data === 'object') {
var convertResult = ""
for(var c in data) {
convertResult += c + "=" + data[c] + "&"
}
convertResult = convertResult.substring(0, convertResult.length - 1)
return convertResult
} else {
return data
}
}
var json = ajax({
url: "http://192.168.10.22:8080/xxx",
dataType: "json",
success: function(msg) {
var date=msg
if(date.stateCode=200){
var result=date.dataList
}
}
},
error: function() {
console.log("error")
}
})
以上是原生js实现,也可以引入jquery 使用$.post()