开发者

Embed raw data in HTML to parse in jQuery

开发者 https://www.devze.com 2023-01-10 21:55 出处:网络
I\'ve been living in the desktop world for most of my career, so forgive me for asking such a basic question, but I\'m not quite sure where to start looking.

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

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 roughly what my js code should look like, but I'm not sure how I should embed the raw data in my HT开发者_StackOverflow社区ML.

I could use $.getJSON(), but it'd be better if I could have the data right in my HTML.

I think either json or XML would work, but what's the proper way to escape/embed/parse these when they're embedded in HTML?

Thanks in advance.


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

For example, we'll take:

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

Escape it and put in a 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's a working example.


Where and when do you want this data?

If you want it 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 view:

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

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

<script>
     var dataArray = [

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

It would be getter if you generated the proper JavaScript in the action instead of the view to avoid 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 in your view:

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


Like you said it is probably best to get it via Ajax using $.post or $.get or $(element).load() etc...

But if you must save it in the page it is common to save in a hidden field. Asp.net saves 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号