开发者

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)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜