开发者

Passing an object-string to a javascript-function

I'm trying to pass a string like this:

{"key":["value"],"key2":undefined,"key3":undefined,"key4":undefined,"key5":"value"}

to a javascript-function like this:

<a 开发者_JAVA技巧href="#" onClick="myFunction(myString);">

but can't get the escaping right. Is there a way to pass that object-string to a function or do I need to convert something?

Greetings, Select0r


try:

var myString = '{"key":["value"],"key2":undefined,"key3":undefined,"key4":undefined,"key5":"value"}';


EDIT:

In light of your recent comment I went back to the browser and tried this (works for me):

<a href="#" onClick="myFunction({'key':['value'],'key2':undefined,'key3':undefined,'key4':undefined,'key5':'value'});">

The change means that it's no longer longer passed as a string but as an object parameter to myFunction.


As Naeem said, you can enclose the string in a single quote. The difference between the single and double quote is this:

single quotes:

  • Can contain double quotes without stopping string
  • Cannot contain characters such as break lines
  • Can contain single quotes via \'

double quotes:

  • Can contain single quotes without stopping string
  • Can contain break line and other special characters
  • Can contain double quotes via \"


I found a solution, Naeem Sarfraz put me on the right track - it's not going to win a beauty contest, but it works:

As I can execute PHP in the context I'm in (but IE6 would ignore Javascript), I did a couple of replacements on single/double quotes with PHP.

$data = stripslashes(unserialize($data));
$data = addcslashes($data, "'");
$data = str_replace('"', "'", $data);

This will strip all slashes, add slashes for single quotes only and finally replace double quotes with single ones.

Now myString is in a state that can be passed to a Javascript function in onclick without quote-conflicts:

<a href="#" onClick="myFunction(<?php print $data; ?>);">

Thanks for your contributions!


If you can generate code just before this <a> element, you can try this:

<script type="text/javascript">
var myObj = {"key":["value"], "key2":undefined, "key3":undefined, "key4":undefined, "key5":"value"};
</script>
<a href="#" onClick="myFunction(myObj)">
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜