I have the following html component to which I pass a Json:
<a href="javascript:abreModal('{ 'name':'John', 'age':'30', 'city':'New York'}');">
Pulsador
</a>
And the Javascript function:
function abreModal(text) {
//var text = '{ "name":"John", "age":"function () {return 30;}", "city":"New York"}';
obj = JSON.parse(text);
alert(obj.name);
}
The error firebug throws me is:
SyntaxError: missing ) after argument list
I suspect that the error is in the quotes abreModal(...)
I have tried to change the quotes without result.
Any suggestion?
Your string is between the two marks I put in, and the next thing you type is
name
instead of a comma (,
) or the closing parenthesis. What I recommend is that you do not send a Json but the object:And so you don't need to parse or anything:
Remember that Json is used to exchange data between server and client, it doesn't make much sense to transform an object into Json and then parse it in the same script.
Now, if the situation is that you receive that Json from somewhere else, then I recommend that you parse it before sending it and send the variable that contains it.
Simply remove the quotes and pass the object as such, so you can access it directly in the function , ie:
You have this:
Simply remove the quotes around the object
And you no longer need to parse anything because you will have a literal object to work with and access its properties.
If you really need to pass a string
JSON
per parameter , then:You could print the
JSON
encoding for URIs, this way single quotes ('
), double quotes ("
) and any other special characters would be escaped, thus preventing the HTML from breaking.in
JS
you can useencodeURIComponent
Example:
A good practice is to use
onclick
and you had single quotes for others, the JSON that you send does not need to be parsed.