[英]How to send a PUT request with payload using POST or GET?
我需要将带有负载的 PUT 请求发送到 API(Philips Hue Bridge),但我在 javascript 中有一些限制。 我只能使用:
open(method, url [, async = true [, username = null [, password = null]]])
设置请求方法、请求 URL 和同步标志。 支持的请求方式:GET、POST
send(data = null)
发起请求。 可选的 'data' 参数只允许使用 UTF-8 编码的字符串类型。 如果请求方法为 GET,则忽略该参数。
abort()
取消任何网络活动。
此限制来自Tizen Wearable Web Widget 规范
网址: http://hostname/api/username/lights/lightKey/state
方法: PUT
负载示例: {"on": true}
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://hostname/api/username/lights/lightLey/state?on=true');
xhr.send();
响应: 400 (Bad request)
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://hostname/api/username/lights/lightLey/state?on=true');
xhr.send();
响应: 400 (Bad request)
还尝试使用以下 URL 结尾的GET
和POST
:
../state?{on=true}
../state?{on:true}
../state?{"on"=true}
../state?{"on":true}
响应: 400 (Bad request)
同样,除了上面提到的 XMLHttpRequest 方法之外,我不能使用任何其他库或命令。
我该如何解决这个问题?
下面是示例代码。 您可以在代码中尝试这种方式。
var http = new XMLHttpRequest();
var url = 'your_URL.php';
var params = 'on=true';
http.open('PUT', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
将method
属性更改为PUT
应该可以解决问题。
var xhr = new XMLHttpRequest();
xhr.open('PUT', 'http://hostname/api/username/lights/lightLey/state?on=true');
xhr.send();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.