Trying to echo JS function in PHP

寵の児 提交于 2019-12-12 02:37:59

问题


I'm trying to echo a js function in HTML string inside PHP echo.

And I can't figure it out :

$MY_JS_FUNCTION = '<script type="text/javascript">item + getLastField2()</script>';

if($row2->type == 'text') {
    echo "<li id='item-".$row2->rank."' class='list_item'>";
    echo "<textarea rows='2' id='".$row2->single_id."' cols='90' name='field[".$MY_JS_FUNCTION."]' data-kind='text' >".$row2->content."</textarea>";
    echo "</li>";
    echo '<br />';
}

Any ideas to get this work? I think I have so much quotes in it or something like that...

Any help would be very very appreciated, thanks!


回答1:


I'd reccommend storing the name in the database as well. Then you can use $row2->name to insert the right name




回答2:


Your variable $MY_JS_FUNCTION contains an HTML <script> tag with some (strange) JavaScript code (missing a semi-colon). Based on your code the echo on line 5 results in this HTML:

<textarea ... name='field[<script type="text/javascript">item + getLastField2()</script>]' ... >...</textarea>

This is definitively not valid HTML. And there is your problem...




回答3:


It appears your intent is to echo that JS so that when the page loads, the JS actually sets the value of the name field for that textarea. If that's the case, a simpler way might be something like this:

$MY_JS_FUNCTION = '<script type="text/javascript">document.getElementById("myTextArea").name = item + getLastField2()</script>';

if($row2->type == 'text') {
    echo "<li id='item-".$row2->rank."' class='list_item'>";
    echo "<textarea rows='2' id='".$row2->single_id."' cols='90' id='myTextArea' data-kind='text' >".$row2->content."</textarea>";
    echo $MY_JS_FUNCTION;
    echo "</li>";
    echo '<br />';
}

That will produce valid HTML. The JS function will fire once that line is reached and update the "name" value to whatever the result of the function is. Be sure to add the "id" field so that the JS knows which element to target.



来源:https://stackoverflow.com/questions/8282708/trying-to-echo-js-function-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!