2014-05-15 20 views
14

我已經在我的網站上使用令牌輸入,這裏是我如何初始化令牌輸入:遺漏的類型錯誤:「在」運營商不能使用搜索'在JSON字符串

$(document).ready(function() {   
    var populateValue = document.getElementById('<%= hiddentokenPrePopulate.ClientID%>').value 
    $("#<%= tokenEmployee.ClientID%>").tokenInput("../Employee/getEmployeeDetails.ashx", { 
     deleteText: "X", 
     theme: "facebook", 
     preventDuplicates: true, 
     tokenDelimiter: ";", 
     minChars: 3, 
     tokenLimit: 1, 
     prePopulate: populateValue 
    }); 
}); 

腳本被卡住在這條線:

prePopulate: populateValue 

當我刪除此行,不會有任何JavaScript錯誤,但我需要這個,因爲我需要預先填充令牌輸入。該populateValue是:

[{ 
    "id": "11566", 
    "name": "Smith - White" 
}] 

有一個JavaScript錯誤:

Uncaught TypeError: Cannot use 'in' operator to search for '47' in [{"id":"11566","name":"Smith - White"}]`

如何解決這個問題?

回答

37

你需要在你的populateValue變量來解析字符串對象:

prePopulate: $.parseJSON(populateValue) 

或者,以純JS:

prePopulate: JSON.parse(populateValue) 
+0

感謝您的回答,它像一個魅力 – User5590

2

你的服務器端代碼意味着,你必須.CS頁編寫你的WebMethod,應該總是返回.ToList()意味着json的排列

這是我的.CS頁面代碼:

的WebMethod

public static string PopulateDetails(Guid id){ 
    var prx = new ProductProxy(); 
    var result = prx.GetFirstorDefault(id); // this method is having List<ClassObject> return type 
    return JsonConvert.SerializeObject(result); 
} 

然後在我的jQuery的POST方法:

$.ajax({ 
    type: "POST", 
    dataType: "json", 
    contentType: "application/json; charset=utf-8", 
    url: "Productjq.aspx/PopulateDetails", 
    data: JSON.stringify({id: id}), // This is Id of selected record, to fetch data 
    success: function(result) { 
     var rspns = eval(result.d); // eval is used to get only text from json, because raw json looks like "Id"\"1234" 

     $.each(rspns, function() { 
      $('#<%=txtProductName.ClientID %>').val(this.Name); 
     }); 
    }, 
    error: function(xhr, textStatus, error) { 
     alert('Error' + error); 
    } 
}); 
2

您可能,如果你使用的是字符串數組得到這個錯誤。假設你從ajax得到一個json,並且忘記解析結果,並將結果作爲一個數組使用。補救措施如上所述,在使用之前解析json。

0

我也遇到了這個錯誤。

C#Api返回序列化字典數據。

return JsonConvert.SerializeObject(dic_data); 
return new JavaScriptSerializer().Serialize(dic_data); 

不停地在收到此錯誤消息,直到我剛剛返回的字典數據的情況下直接試圖在瀏覽器端序列化

return dic_data; 

沒有更多的錯誤。不知道爲什麼。

相關問題