开发者

Why is my PHP output scrambled when I provide an input for the printed javascript call?

开发者 https://www.devze.com 2023-04-01 08:35 出处:网络
I\'m generating HTML code in a PHP file, and then returning the result to an AJAX function to include it in an already loaded web-page.

I'm generating HTML code in a PHP file, and then returning the result to an AJAX function to include it in an already loaded web-page.

My code is:

$schoolName=$row->name;
echo "<td><b onclick=\"selectSchool(\"$schoolName\")\">$schoolName</b></td><td>{$row->stateName}</tr>";开发者_运维百科

The expected result would be:

<td><b onclick="selectSchool("Foo")">Foo</b></td>

But what I get is an ugly melange:

<td><b angeles)")"="" (los="" university="" lincoln="" abraham="" onclick="selectSchool(">Abraham Lincoln University (Los Angeles)</b></td>

If I were simply getting an un-desireable result I wouldn't be so concerned, but for some reason the output is becoming totally scrambled and I have no clue why. I cannot figure out where things like 'los=""' are coming from!

If I don't use a variable inside the selectSchool() function call, then I get the expected output, but that's not useful at this point, I need to be able to pass the appropriate value into the function for it to work!

Requested var_dump:

string 'Abraham Lincoln University (Los Angeles)' (length=40)

object(stdClass)[3]
  public 'name' => string 'Abraham Lincoln University (Los Angeles)' (length=40)
  public 'stateName' => string 'California' (length=10)


Why don't you just use single quotes when passing parameter to selectSchool() like this?

<td><b onclick=\"selectSchool('$schoolName')\">$schoolName</b></td><td>{$row->stateName}</tr>";

That way you'll get the following result

<td><b onclick="selectSchool('Foo')">Foo</b></td>

This won't break the HTML


I guess it's because you have quotes in your text (") you should pass your $schoolNamevariable throw addslashes function.

0

精彩评论

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