Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

php object passing to javascript function does not work despite using htmlspecialchars

In a php function I receive a resultset "$pRecord" that can be extracted with extract($pRecords) .. works fine, t.e. I get variables $name , $description... Now I want to pass this resultset to a javascript function this way:

<img onclick='var myObj = .....; myfunc(myObj)'/>

Clicking the image I get the error:

Uncaught SyntaxError: expected expression, got '}'.

My original code is:

$SEG = "var wObj = JSON.parse('".htmlspecialchars(json_encode($pRecord))."'); ";
$OMCsl = "$SEG Segment.showSegmentlanesBox(wObj);";
$Z .= "<img class='segs' onclick='$OMCsl' src='$this->iconpath/segmentlanes.png' title='id=$id'/>";
echo $Z;

Leaving htmlspecialchars away yields the same error.

What's the problem?

question from:https://stackoverflow.com/questions/65541123/php-object-passing-to-javascript-function-does-not-work-despite-using-htmlspecia

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Remove htmlspecialchars and quotes around JSON object.

$SEG = "var wObj = JSON.parse(" . json_encode($pRecord) . "); ";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...