簡體   English   中英

如何使用 POST 或 GET 發送帶有負載的 PUT 請求?

[英]How to send a PUT request with payload using POST or GET?

我需要將帶有負載的 PUT 請求發送到 API(Philips Hue Bridge),但我在 javascript 中有一些限制。 只能使用:

XMLHttpRequest 方法:

open(method, url [, async = true [, username = null [, password = null]]])
設置請求方法、請求 URL 和同步標志。 支持的請求方式:GET、POST

send(data = null)
發起請求。 可選的 'data' 參數只允許使用 UTF-8 編碼的字符串類型。 如果請求方法為 GET,則忽略該參數。

abort()
取消任何網絡活動。

此限制來自Tizen Wearable Web Widget 規范


飛利浦 Hue Bridge API 期望:

網址: 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 結尾的GETPOST
../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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM