开发者

jquery noob: cannot parse json

im an experienced .net developer, but just new to jquery.

im trying to fill a select dropdown via jquery

it aint working so im trying first something basic

<script type=开发者_JAVA百科"text/javascript">
    $(document).ready(function () {
        $('select[name*="edtPersonID"]').change(function () {
            fillAddresses('[{"Foo": "Bar"}]');
        });
    });
    function fillAddresses(jsRes) {
        alert(jsRes[0].Foo);
    }
</script>

as far as i read, the "jsRes" should somehow be converted to an array, so that jsRes[0] will return the first object in the array

but what the alert actually brings is just "undefined"

if i check jsRes[0] it equals to "[" meaning that its considered a string not an array

how can that be fixed?

the end code would probably use getJson to access a webservice for the values, and then id use some loop to add them to the options of the select

thank you vey much for your time and patience


'[{"Foo": "Bar"}]' defines string. To define array, remove quotes: [{"Foo": "Bar"}]. Just like in C#.

You can also use eval to execute js code in a string (and to convert json string to js object in particular). eval('([1, 2])') returns array [1, 2].
Since you said you plan on getting this string from web service, it might be useful.

About eval


fillAddresses('[{"Foo": "Bar"}]');

to

fillAddresses([{"Foo": "Bar"}]);

basically drop the single quotes:)

Cheers

G.


You are confusing JavaScript literal objects with JSON. In JavaScript, you can define an object with the {} notation, e.g.:

var president = {
    name: "John",
    age: 33
};

And there is a data exchange format called JSON that uses a subset of the JavaScript syntax to encode stuff:

{"name":"John","age":33}

When a JSON string reaches your JavaScript program, it's just a string:

var json = '{"name":"John","age":33}';

... not different from any other string:

var notJson = 'Hello, World!';

With time and ability, you can use JavaScript string handling functions to analyse this string and extract the original values encoded in the string into regular JavaScript variables. jQuery does it for you automatically when you load a JSON string through AJAX functions.

However, your code snippet is not using JSON to exchange data between programs or computers. Thus you don't really need JSON: you can pass the values directly, the same way that you'd pass an integer.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜