在php中构建JavaScript

i been now hanging on this for like a hour and cant finde the problem. Its driving me crazy

$script .=nl().'$(this).html("<img src="'.CDN('/icons/loading/loading5.gif').'" />");';

i get the error:

SyntaxError: missing ) after argument list


$(this).html("<img src="https://cdn.connexservice.com/icons/loading/loading5.gif...

and the arrow showson the h of the https.. I must been missing a ' or a " somewhere... Hopefully some one got a better eye on this..

bah.. quick edit, found the problem, but , it wont show the gif.

$script .=nl(). '$(this).html("<img src=\''.CDN('/icons/loading/loading5.gif').'\' />");';

this is shown in the source code:

$(this).html("<img src=\"https://cdn.connexservice.com/icons/loading/loading5.gif\" />");

You need to escape the quotes in your HTML using \:

$script .=nl().'$(this).html("<img src=\"'.CDN('/icons/loading/loading5.gif').'\" />");';

You have to escape your quotation marks:

$script .= nl() . '$(this).html("<img src=\"' . CDN('/icons/loading/loading5.gif') . '\" />");';

To apply proper escaping everywhere, I prefer writing it out like this:

$script .= nl() . sprintf('$(this).html(%s);',
        json_encode(sprintf('<img src="%s" />', CDN('/icons/loading/loading5.gif')))
);

I'm using two sprintf() calls; the first is to build the HTML string, the second is to build the JavaScript code.

Additionally it uses json_encode() to make sure the string is properly escaped.