开发者

What techniques do you use for emitting data from the server that will solely be used in client side scripts?

I never found an optimal solution for this pr开发者_开发百科oblem so I am hoping that some of you out there have a few solutions.

Let's say I need to render out a list of checkboxes and each checkbox has a set of additional data that goes with it. This data will be used purely in the context of javascript and jquery. My usual strategy is to render this data in hidden fields that are grouped in the same container as the checkbox.

My rendered HTML will look something like this:

<div>
  <input type="checkbox" />
  <input type="hidden" class="genreId" />
  <input type="hidden" class="titleId" />
</div>

My only problem with this is that the data in the hidden fields get posted to the server when the form is submitted. For small amounts of data, this is fine. However, I frequently work with large datasets and a large amount of data is needlessly transferred.

UPDATE: Before submitting this post, I just saw that I can add a "DISABLED" attribute to my input element to suppress the submission of data. Is this pretty much the best approach that I can take?

Thanks


Why not convert your data (of whatever form) into a JSON string and echo that into a JavaScript variable? Then you can do whatever you want with it and you're not sending all kinds of extra parameters with your form submissions. In PHP, this would look something like this:

<script type="text/javascript">
     var data = <?php echo json_encode($data) ?>;
</script>

For more info on converting objects to JSON format in ASP, check out these links:

Any good libraries for parsing JSON in Classic ASP?

http://code.google.com/p/aspjson/


Yeah. You can use json for that, or simply use the jQuery.data <http://api.jquery.com/jQuery.data/>. It'll store some values in the element that you wish.


If anyone else is reading this and is interested in a solution, you can use HTML5 custom data attributes. I know that HTML5 is still a working draft, but this concept seems to be approved. This allows me to strongly tie data to the element in question. In the case of my problem, I can now associate genreId and titleId directly to the checkbox instead of grouping hidden fields with the checkbox. Not exactly groundbreaking, but it's nice to know that custom attributes are now part of the specification.

Example:

More info: http://dev.w3.org/html5/spec/Overview.html#custom-data-attribute

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜