Ben Williams
Ben Williams

Reputation: 131

Strange behaviour with asp.net and javascript array

This follows on from my question earlier about Visual Studio showing "" instead of ".

When I run the code below it creates a javascript array and returned as res[0] like below:

["Name","Name","Name"]

in visual studio it returns this:

"["Name","Name","Name"]"

When I run the code, this part shows the surrounding speech marks still (autocompletedata):

autocomplete(document.getElementById("rd-search-form-input"), autocompletedata );

This causes the code to not work. When i manually remove the surrounding double quotes, all works fine.

I've tried removing the start and end part of the string but it just removes the [ and ], which indicates that the string isn't surrounded by double quotes at all. I've also tried removing all double quotes but to no avail.

Can anyone explain whats going wrong?

var urlMethod = "/ajax.aspx/GetTeamMemberNamesList";
var params = new Object();
var result;

params.TeamID = 123;

result = SendAjaxSingleValue(urlMethod, params);
var res = result.d.split("|");

var autocompletedata = res[0];

autocompletedata.replace(/['"]+/g, '')

autocomplete(document.getElementById("rd-search-form-input"), autocompletedata );

Upvotes: 1

Views: 45

Answers (2)

Ben Williams
Ben Williams

Reputation: 131

Well, this was annoying - this fixed my issue:

autocomplete(document.getElementById("rd-search-form-input"), JSON.parse(autocompletedata));

Upvotes: 0

DKyleo
DKyleo

Reputation: 826

To clarify the solution from the OP, the ajax call returns not the array itself but a JSON string, as is always the case when receiving data from a web server - hence why res[0] is returned as ["Name","Name","Name"].

Hence, in order to turn the response text into an actual array, it requires JSON.parse to perform the conversion.

Upvotes: 2

Related Questions