简体   繁体   中英

JSON String as Javascript function argument

I am trying to define a pure JSON string as an argument in a Javascript function.

Below is the way I want to define it:

<a href="#" onclick="js_func('arg_1', 'arg_2', '{"key": "value"}'); return false">Link</a>

Firebug gives me an error alert: unterminated string literal, even when I escape the double-quotes on the JSON string.

How can I solve this?

Thanks.

Use &quot; for your double quotes, then in js_func() , replace them with actual double quote characters ( " ) before evaluating your JSON string. (thanks for the demo Matthew, I updated your fiddle with the example from the question:)

http://jsfiddle.net/brillyfresh/kdwRy/1/

simply defining the link as <a href="#" onclick="js_func('arg_1', 'arg_2', {key: 'value1'}); return false;">Link</a> works fine. JSON is valid JavaScript, you don't need to enclose it in ''s.
I also suggest to use an EventListener ( element.addEventListener() ), this makes the html cleaner and would reduce this problem to nothing.

ryou are either trying to pass the parsed object or pass a string

Object: onclick="js_func(arg_1, arg_2, {'key': 'value'});"

String: on_click="js_func('arg_1', 'arg_2', '{\"key\": \"value\"}'); return false"

All I've got handy to test is firebug interpreter but both worked fine for me.

>>>>'{\"key\": \"value\"}'
"{"key": "value"}"
>>>> {'key': 'value'}
Object {key="value"}

(I don't mean to presume whether arg_1 and arg_2 are strings or variable names, and it doesnt matter. just did the same thing as with the JSON)

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