简体   繁体   English

JSON String作为Javascript函数参数

[英]JSON String as Javascript function argument

I am trying to define a pure JSON string as an argument in a Javascript function. 我试图在Javascript函数中将纯JSON字符串定义为参数。

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. Firebug给了我一个错误警告:未终止的字符串文字,即使我在JSON字符串上转义双引号也是如此。

How can I solve this? 我怎么解决这个问题?

Thanks. 谢谢。

Use &quot; 使用&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:) 对于你的双引号, 然后在 js_func() ,在评估你的JSON字符串之前用实际的双引号字符( " )替换它们。 (感谢演示Matthew,我用问题中的例子更新你的小提琴:)

http://jsfiddle.net/brillyfresh/kdwRy/1/ 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. 只需将链接定义为<a href="#" onclick="js_func('arg_1', 'arg_2', {key: 'value1'}); return false;">Link</a> JSON is valid JavaScript, you don't need to enclose it in ''s. JSON是有效的JavaScript,你不需要将它包含在内。
I also suggest to use an EventListener ( element.addEventListener() ), this makes the html cleaner and would reduce this problem to nothing. 我还建议使用EventListener( element.addEventListener() ),这使得html更清晰,并将此问题减少为空。

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. 我所有的方便测试是firebug解释器,但两者都适合我。

>>>>'{\"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) (我不是要假设arg_1arg_2是字符串还是变量名,并不重要。只是做与JSON相同的事情)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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