Reputation: 22485
I have a novel problem that I've never had to deal with before and to which a search on SO and google has failed to resolve.
I'm querying a webservice via an ajax call to my controller that returns the contents of a javascript file. Inside this javascript file, there is a primitive array, structured as follows:
var myData = [
['A', 'A', 'C', 'more elements...'],
['X', 'Y', 'Z', 'more elements...']
];
I'm parsing this out to a string and am passing that back to my view (as a MvcHtmlString
) and am hoping that i can deserialize that back to a primitive array inside my view. So far, I've tried the following without success:
1.
<script>
$(function() {
setInterval(refreshData, 5000);
});
function refreshData() {
$.ajax({
url: '@Url.Action("GetLatestJsData", "Home")',
context: document.body
}).done(function (data) {
console.log(jQuery.parseJSON(data));
// i also tried not parsing with the same result
});
}
</script>
(btw -i've also attempted sending the string back from my controller in the following format, which also failed to work:
[
['A', 'A', 'C', 'more elements...'],
['X', 'Y', 'Z', 'more elements...']
];
I can understand why none of the above works, as the array is not a valid json type. However, defining this same array inside a javascript block does indeed work, so I'm wondering what type of processing in jquery/javascript is required in order to deserialize this string out to a primitive array as required.
I am aware that with some grunt, I could work inside my c# code to make a c# array and then pass that to a JsonResult, however, I'd like to discover how to pass this string straight back to the ajax success handler and deserialize it from there, as this will be an ongoing requirement, thus would like to somehow do a straight pass-tho of the string from the file and back out to the same array type on the client.
I look forward to a variety of approaches.
Upvotes: 0
Views: 119
Reputation: 4218
did you try eval()?
<script>
$(function() {
setInterval(refreshData, 5000);
});
function refreshData() {
$.ajax({
url: '@Url.Action("GetLatestJsData", "Home")',
context: document.body
}).done(function (data) {
eval(data);
console.log(myData);
});
}
</script>
Upvotes: 1