使用AngularJS通过POST传递参数还是需要设置一些东西才可以!
1、不能直接使用params
例如:
[javascript] view plain copy
$http({
method: "POST",
url: "http://192.168.2.2:8080/setId",
params: {
cellphoneId: "b373fed6be325f7"
}
}).success()
当你这样写的时候它会把id写到url后面:
[javascript] view plain copy
http://192.168.2.2:8080/setId?cellphoneId=b373fed6be325f7"
会在url后面添加"?cellphoneId=b373fed6be325f7",查了些资料发现params这个参数是用在GET请求中的,而POST/PUT/PATCH就需要使用data来传递2、直接使用data
[javascript] view plain copy
$http({
method: "POST",
url: "http://192.168.2.2:8080/setId",
data: {
cellphoneId: "b373fed6be325f7"
} }).success()
这样的话传递的,是存在于Request Payload中,后端无法获取到参数
这时发现Content-Type:application/jsoncharset=UTF-8,而POST表单请求提交时,使用的Content-Type是application/x-www-form-urlencoded,所以需要把Content-Type修改下!
3、修改Content-Type
[javascript] view plain copy
$http({
method: "POST",
url: "http://192.168.2.2:8080/setId",
data: {cellphoneId: "b373fed6be325f7"},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success()
这时数据是放到了Form Data中但是发现是以对象的形式存在,所以需要进行序列化!
4、对参数进行序列化
[html] view plain copy
$http({
method: "POST",
url: "http://192.168.2.2:8080/setId",
data: {cellphoneId: "b373fed6be325f7"},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function(obj) {
var str = []
for (var s in obj) {
str.push(encodeURIComponent(s) + "=" + encodeURIComponent(obj[s]))
}
return str.join("&")
}
}).success()
首先,请求的网址要写完整,就是要和postman中一样要加上 /api/updatedata
其次,返回的数据是个json对象,所以直接显示是不行的,要这样 alert(data.data)
以Ajax方式发送<script type="text/javascript">
一、获取url所有参数值
function US() {
var name, value
var str = location.href
var num = str.indexOf("?")
str = str.substr(num + 1)
var arr = str.split("&")
for (var i = 0 i < arr.length i++) {
num = arr[i].indexOf("=")
if (num > 0) {
name = arr[i].substring(0, num)
value = arr[i].substr(num + 1)
this[name] = value
}
}
}
二、使用JS 发送JSON格式的POST请求
var us = new US()
var xhr = new XMLHttpRequest()
xhr.open("POST", "/searchguard/api/v1/auth/login", true)
xhr.setRequestHeader("Content-type", "application/json")
xhr.setRequestHeader("kbn-version", "5.3.0")
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
window.location.href = us.nextUrl
}
}
}
xhr.send(JSON.stringify({
"username" : us.u,
"password" : us.p
}))
</script>