Paste raw data into HTML for analysis in jQuery

I have been living in the desktop world for most of my career, so forgive me for asking this basic question, but I'm not quite sure where to start.

I want to return some raw data along with my HTML, and parse and display the data using jQuery as soon as the HTML is ready. I know exactly what my js code should look like, but I'm not sure how I should embed the raw data in my HTML.

I could use $ .getJSON (), but it would be better if I had data right in my HTML.

I think either json or XML will work, but what is the right way to avoid / insert / parse them when they are embedded in HTML?

Thanks in advance.

+7
json javascript html xml asp.net-mvc
source share
3 answers

You can put JSON data in a hidden div, then decode and use from jQuery.

For example, we take:

{"foo":"apple","bar":"orange"} 

Exit it and paste the div:

 <div id="data">%7B%22foo%22%3A%22apple%22%2C%22bar%22%3A%22orange%22%7D</div> 

Then from jQuery we can use the data:

 var data = jQuery.parseJSON(unescape($("#data").html())); 

So calling alert(data.foo) will give us apple .

Here is a working example.

+7
source share

Where and when do you want this data?

If you want this in your view, just pass the data to the view

Action / Controller:

 public ActionResult MyAction() { ViewData["MyData"] = "this is a sample data of type string"; return View(); } 

And then, somewhere in your opinion:

 <script> var data = '<%= ViewData["MyData"] %>'; $(document).ready(){ alert(data); } </script> <h1><%: ViewData["MyData"] %></h1> 

Of course, if you are working with List<string> or `string [] ', you need to format it for proper JavaScript for jQuery to understand it.

 <script> var dataArray = [ <% foreach(string s in (string[])ViewData["MyDataArray"]){ %> <%= s %>, <% } %> ]; </script> 

This will getter if you created the correct JavaScript in action instead of the view, to avoid the ugly markup in your view:

 public ActionResult MyAction() { string[] myArray = new string[]{ "hello", "wolrd" }; ViewData["MyData"] = myArray; ViewData["JavaScriptArray"] = "[" + myArray.Aggregate((current,next) => string.Format("'{0}','{1}',", current, next).TrimEnd(new char[] { ','})) + "]"; // or you can use your favorite JavaScript serialize return View(); } 

Now you can do the following on your screen:

 <script> var dataArray = <%= ViewData["MyJavaScriptArray"] %>; alert(dataArray[0]); // alerts 'hello' </script> 
+5
source share

As you said, it is best to get it through Ajax using $ .post or $ .get or $ (element) .load (), etc.

But if you have to save it on the page, then usually save it in a hidden field. Asp.net stores things in hidden fields using binary serialization and Base64, but you can save it as a Json string and then use it in your JS.

+1
source share

All Articles