簡體   English   中英

無法在Javascript / Typescript中解析從客戶端服務器發送的對象

[英]Unable to parse object sent from server on client side in Javascript/Typescript

我用TypeScript編寫了一個基於骨架JS的javascript程序,其中服務器將帶有結構化數據的對象發送給客戶端,但我無法在客戶端中成功解析該對象。 該代碼是Typescript接口的實現,該接口接受來自服務器的數據或錯誤,以便為客戶端進行調用。

Typescript接口是這樣的:

interface PersistenceOptions {
        url?: string;
        beforeSend?: (jqxhr: JQueryXHR) => void;
        success?: (modelOrCollection?: any, response?: any, options?: any) => void;
        error?: (modelOrCollection?: any, jqxhr?: JQueryXHR, options?: any) => void;
    }

這是成功函數的代碼,無法呈現“響應”數據

success:function(modelOrCollection?: any, response?: any, options?: any){
                $holder.append(response.toString());
            }

這是進行REST調用時實際對象的外觀:

[
  {
    "id": 0,
    "answer": "I like the device",
    "type": 0
  },
  {
    "id": 0,
    "answer": "Im not sure if I want it",
    "type": 0
  },
  {
    "id": 0,
    "answer": "This is a great device",
    "type": 0
  },
  {
    "id": 0,
    "answer": "I like it but its expensive",
    "type": 0
  }
]

屏幕上的實際輸出如下所示:

[object Object],[object Object],[object Object],[object Object]

我希望能夠解析並以編程方式操縱輸出。 不確定如何。

(我也想知道這是一種什么樣的對象以及如何創建新對象。)

您不能直接輸出對象。 您必須循環對象的屬性,並且由於對象位於數組中,因此必須遍歷數組。 您可以使用map()

success: function (modelOrCollection ? : any, response ? : any, options ? : any) {
    response.map(function (object) {
        for (prop in object) {
            $holder.append(prop + ':' + object[prop] + '<br/>');
        }
    });
}

的jsfiddle

暫無
暫無

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

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