开发者

Yet i'm finding difficult to understand JSON

hey guys, i have read This post, so what i got is JSON is the easiest way to translate a JavaScript object into a PHP/C# associative array or object (and vice-versa).

Now my question is what is goin' on in below code,i.e without JSON/XML i'm still can access my C# object in Javascript, may be i'm wrong, if so Please correct me:

C#

    Foreach(DataRow dr in dvItems.Table.Rows) //dvItems is a DataView
    {
        strItems &= "'" & dr("ItemTitle") & "',"  //strItems is a String
    }
    strItems = strItems.Trim(",")

Javascript : here i'm using Autocomplete.js using JQuery

   function InitAutocomplete() 
   {
       data = [<%=strItems %>].sort();
       AutoComplete_Create('<%=txtItem.ClientId %>', data);
   }

See i'm using str开发者_如何转开发Items in javascript with servertag, so where exactly the JSON is used ? is .net doin' something internally ? i'm totally confused how JSON/XML is used to data passing ?


While you can pass data like this without using JSON, it doesn't ensure that all of the data is safe to pass, e.g. embedded </script> tags. Using JSON will encode your data in a way that prevents this, and you decode it on the JavaScript side with e.g. json2.js.


You're not really using JSON in anything here. You're merely generating an array of strings for javascript and use it in a vvery straightforward manner.

If you wish to transform the JSON to javascript object(s) you need to modify your program and you need a JSON parser. There are several implementations of JSON-parsers, but you mentioned jQuery so you could use: http://api.jquery.com/jQuery.parseJSON/

Parsing with jQuery, however, requires your JSON to be strictly formatted (from v1.4). See http://json.org/ about the correct form. Basically in your situation you should put double quotes around your strings and put the whole array inside square brackets.

Your results should be something like this:

strItems = '['
Foreach(DataRow dr in dvItems.Table.Rows) //dvItems is a DataView
{
    // TODO: Escape dr("ItemTitle") so it conforms to http://json.org/ => String
    strItems &= "\"" & dr("ItemTitle") & "\","  //strItems is a String
}
strItems = strItems.Trim(",")
strItems &= ']'

<script type="text/javascript">
    var jsonArr = <%=strItems%>;
    var data = jQuery.parseJSON(jsonArr);
    AutoComplete_Create('<%=txtItem.ClientId %>', data);
</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜