簡體   English   中英

Javascript Vanilla Ajax將響應轉換為對象數組?

[英]Javascript vanilla ajax turn response into array of objects?

我正在嘗試更深層次的javascript。 我正在構建自己的具有自己的http方法的$http對象。

var $http = {

    get: function(url, success, error) {
        httpHelper('GET', url, success, error);
    }

};

function httpHelper(type, url, success, error) {
    var xmlhttp;
    xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
            if(xmlhttp.status == 200){
                success(xmlhttp.responseText);
            }
            else if(xmlhttp.status == 400) {
                error(xmlhttp.status);
            }
            else {
                error(xmlhttp.status);
            }
        }
    }

    xmlhttp.open(type, url, true);
    xmlhttp.send();
};

在服務器上,我返回帶有請求的JSON對象數組。

app.get('/api/players/', function(req, res) {
  res.json([
    { name: 'Mike', points: 33 }, 
    { name: 'Shaq', points: 16 }
  ]);
});

在客戶端上,我似乎收到了一個字符串[{"name":"Mike","points":33},{"name":"Shaq","points":16}]

如何有效地將客戶端響應轉換為JSON對象數組?

只需使用JSON.parse

JSON.parse(xmlhttp.responseText);

即使評論已經回答了這個問題,我還是覺得我應該拋出一個實際的答案(還要澄清放置位置!)

您正在尋找JSON.parse 放置的位置取決於$http對象是否僅獲取JSON響應。 如果是這樣,則將JSON.parse放入success發送的內容中:

success(JSON.parse(xmlhttp.responseText));

但是,如果您還想接受其他類型的請求,則將JSON.parse放入成功的回調中。

$http.get('some url', function(result) {
    result = JSON.parse(result);
}, function() {
    // ...
});

暫無
暫無

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

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