簡體   English   中英

帶有JSON數據的Javascript HTTP POST

[英]Javascript HTTP POST with JSON data

我可以發送如下請求嗎? 為參數分配JSON樣式對象。 我只得到錯誤。 但是當我使用REST客戶端並選擇RAW數據時,沒關系。 我想我必須寫錯了代碼。 如何在JavaScript中發送原始JSON數據? 誰能幫助我?

xmlhttp = new XMLHttpRequest();
var url = "https://someURL";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        alert(xmlhttp.responseText);
    }
}
var parameters = {
    "username": "myname",
    "password": "mypass"
};
// Neither was accepted when I set with parameters="username=myname"+"&password=mypass" as the server may not accept that
xmlhttp.send(parameters);

不行send()方法可以采用許多不同的參數類型 ,但普通對象不是其中之一(因此最終可能會在其上調用toString()並轉換為"[Object object]" )。

如果你想發送JSON,你必須:

  1. 假設您要發送JSON: xmlhttp.setRequestHeader("Content-type", "application/json");
  2. 將JavaScript對象轉換為JSON文本字符串: var parameters = JSON.stringify({"username":"myname","password":"mypass"});
  3. 准備好在服務器端接受JSON而不是application / x-www-form-urlencoded數據。

另請注意,由於您使用的是絕對 URI,因此可能會遇到跨域問題

xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", AjaxURL, true);
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
cb(xmlhttp.responseText);               
}
};
xmlhttp.send(JSON.stringify(Idata)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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