【发布时间】:2016-11-21 18:26:07
【问题描述】:
编辑:这可能是后端 API 的问题吗?通过 $.param 发送的数据请求总是字符串,对吗?所以他们需要在后端解析这些东西?
我目前正在尝试向 API 发送发布请求以注册用户。其中一项要求是接受条款和条件以及年龄要求,它需要一个布尔值。
我认为问题可能是 $http 请求正在向 API 后端发送一个字符串而不是布尔值,因此它拒绝了它。如何通过 $http 发送布尔值?
var apiCall = {
method: 'POST',
url: 'API_URL',
data: $.param({
'user[email]': username,
'user[password]': password,
'user[password_confirmation]':password,
'profile[age_acceptance]': ageAcceptance,
'profile[terms_acceptance]': termsAcceptance
}),
headers: {
'Accept': 'application/vnd.softswiss.v1+json',
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function(data, headersGetter, status) {
console.log(data);
console.log(headersGetter(data));
}
}
【问题讨论】:
-
尝试使用 console.log 语句(或开发工具调试器)查看
typeof termsAcceptance返回的内容。然后你就会确定这是否是类型的问题。 -
已经完成。传递给 $.param 的值是布尔值——但是当我记录转换请求时,它只是一个大字符串(这可能是正常的,但我只是想弄清楚为什么我会被 API 拒绝)。
-
您的 API 是否接受
'Content-Type': 'application/json'而不是x-www-form-urlencoded? -
不使用jQuery参数编码器,而是使用$httpParamSerializer serviceDEMO on JSFiddle
-
这个好像和$.param功能一样,有什么优势呢? (没有解决问题,只是好奇)。