简体   繁体   中英

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,ie 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 strItems 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, eg embedded </script> tags. Using JSON will encode your data in a way that prevents this, and you decode it on the JavaScript side with eg 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM