I've use token input in my website, and here's how I initialize the token input:

$(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
    });
});

The script was stuck on this line:

 prePopulate: populateValue

When I remove this line, there won't be any javascript error, but I need this as I need to pre-populate the token input. The populateValue is:

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

There was a javascript error:

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

How can I fix this error?

有帮助吗?

解决方案

You need to parse the string in your populateValue variable to an object:

prePopulate: $.parseJSON(populateValue)

Or alternatively, in plain JS:

prePopulate: JSON.parse(populateValue)

其他提示

You may get this error if you are using a string as an array. Say that if you got a json from an ajax, and you forgot to parse the result, and using the result as an array. The remedy is as above, to parse the json before using it.

Your server side code means .CS page where you have written your WebMethod, should always return .ToList() means array of json

Here is my .CS page code:

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);
}

Then in my jQuery post method:

$.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);
    }
});

I was getting this error as well.

C# Api returning Serialized Dictionary data.

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

Kept on getting this error message, until i just returned the Dictionary data directly without trying to Serialize

return dic_data;

No more errors on the browser side. Not sure why.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top