开发者

Javascript error while executing alert function through php

I am using fusion maps in one of my application.

In one of the example i have to pass the value from one map to another charts,

I am facing one problem if the data passed is numeric its displaying alert message correctly but if it is a string it generates an error:

NM is not defined

javascript:alert(NM)()

My code is as below:

$strXML .= "<entity id='" . $rs1['Internal_Id'] . "' value='" . round((($rs1['datap'] /  $sumdata) * 100),2) . "' link='javascript:alert(".($rs1['Internal_Id']) . ")'  />";

If i change the link part (passing single quotes in alert)that is:

$strXML .= "<entity id='" . $rs1['Internal_Id'] . "' value='" . round((($rs1['datap'] /  $sumdata) * 100),2) . "' link='jav开发者_JAVA技巧ascript:alert('".($rs1['Internal_Id']) . "')'  />";

It displays invalid xml data.

Please help me on this

Thanks

Pankaj


Use \" rather than ' to surround the JavaScript string.

$strXML .= "<entity id='" . $rs1['Internal_Id'] . "' value='" . round((($rs1['datap'] /  $sumdata) * 100),2) . "' link='javascript:alert(\"".($rs1['Internal_Id']) . "\")'  />";

What is happening is that the xml produced is like so:

<entity id='NM' value='1' link='javascript:alert('NM')'/>

Which as you should be able to see from SOs syntax highlighting ends the value for the link attribute after javascript:alert(' as you are using the same quotes for the javascript as you are using for surrounding the attribute values.

Using a different quote (" rather than ') doesn't end the attribute value (again see the syntax highlighting)

<entity id='NM' value='1' link='javascript:alert("NM")'/>


In PHP we have to escape the quote (Using \) so it isn't interpreted as a special character by the php interpreter and used to end the string, which is why in php you have to write \"


You should change your

ink='javascript:alert('".($rs1['Internal_Id']) . "')'

by

ink='javascript:alert(\"".($rs1['Internal_Id']) . "\")'


Try:

$strXML .= "<entity id='" . $rs1['Internal_Id'] . "' value='" . round((($rs1['datap'] /  $sumdata) * 100),2) . "' link='javascript:alert(\"".($rs1['Internal_Id']) . "\")'  />";

Basically escaping your alert quotation marks :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜