2013-05-08 53 views
1

創建的字符串數組是如何通過帶鬍鬚的json字符串集合進行循環?

public JsonResult GetInvalidFilesAJAX(JQueryDataTableParamModel param) 
    { 
     string[] invalidFiles = new string[] { "one.xls", "two.xls", "three.xls" }; 

     return Json(new 
     { 
      Status = "OK", 
      InvalidFiles = invalidFiles 
     }); 
    } 

的MVC和JavaScript應該循環並打印出每個字符串

$.ajax(
          { 
           type: 'POST', 
           url: 'http://localhost:7000/ManualProcess/GetInvalidFilesAJAX', 
           success: function (response) { 
            if (response.Status == 'OK') { 
             //Use template to populate dialog with text of Tasks to validate 
             var results = { 
              invalidFiles: response.InvalidFiles, 
             }; 
             var template = "<b>Invalid Files:</b> {{#invalidFiles}} Filename: {{invalidFiles.value}} <br />{{/invalidFiles}}"; 
             var html = Mustache.to_html(template, results); 

             $('#divDialogModalErrors').html('ERROR: The following files have been deleted:'); 
             $('#divDialogModalErrorFiles').html(html); 

如何我指的是字符串數組中?上面的方式是不正確的。我發現的所有例子似乎都是爲了當傑森系列有屬性名稱..在我的情況下,它只是一個關鍵值對(我猜?)

回答

1

沒有內置的方式。必須將JSON轉換成通過數據自己,例如數組或循環,

var data = JSON.parse(jsonString); // Assuming JSON.parse is available 
var arr = []; 
for (var i = 0, value; (value = data[i]); ++i) { 
    arr.push(value); 
} 

或者:

var arr = []; 
for (var prop in data){ 
    if (data.hasOwnProperty(prop)){ 
    arr.push({ 
     'key' : prop, 
     'value' : data[prop] 
    }); 
    } 
} 

然後以顯示它:

var template = "{{#arr}}<p>{{value}}</p>{{/arr}}"; 
var html = Mustache.to_html(template, {arr: arr}); 

這是假設你的JSON對象是一個深度。

+0

我不能得到下面的行工作..究竟應該放在'jsonString'位置? var data = JSON.parse(response.InvalidFiles); – punkouter 2013-05-08 19:05:17

+0

@punkouter您收到的JSON字符串作爲迴應。如果它已經是一個JSON對象,那麼就把'data = object'。你可以'console.log(response.InvalidFiles)'爲我嗎? – 2013-05-08 19:06:12

+0

one.xls,two.xls,three.xls ..所以我想這是一個JavaScript數組,而不是一個JSON對象嗎? – punkouter 2013-05-08 20:04:44