将PHP变量嵌套在Javascript onClick方法中

时间:2018-08-16 18:24:24

标签: javascript php html

我的代码:

function count_words_display($speech, $articleid){

    if (str_word_count($speech)>200){

    $speech_short = implode(' ', array_slice(explode(' ', $speech), 0, 100)).'...<input type="button" id="read" value="Read more" onclick="myFunction("'.$articleid.'","'.$speech.'")">';
    print $speech_short;
}
else{

    print $speech;
    }
}

我打算获得与此类似的输出:

<input type="button" id="read" value="Read more" onclick="myFunction('24','Play')";>

但是,我最终得到了这一点:

<input type="button" id="read" value="Read more" onclick="myFunction("24","Play")";>

导致此错误:

SyntaxError: expected expression, got '}'

3 个答案:

答案 0 :(得分:0)

尝试一下:

class JsonRpcRequest
{
    public int? id;
    public string jsonrpc;
    public string method;
    public object @params;
}

class AddParam
{
    public int a;
    public int b;
}

static void Main(string[] args)
{
    var p = new AddParam()
    {
        a = 100,
        b = 200,
    };
    var request = new JsonRpcRequest()
    {
        jsonrpc = "2.0",
        method = "Add",
        @params = p,
    };

    var stream = new MemoryStream();
    var reader = new StreamReader(stream);
    var writer = new StreamWriter(stream);
    var ser = new JsonSerializer();

    request.id = 100;
    ser.Serialize(writer, request);
    writer.Flush();
    // stream.Position is 68
    request.id = 101;
    ser.Serialize(writer, request);
    writer.Flush();
    // stream.Position is 136
    stream.Position = 0;

    // Stream holds
    // {"id":100,"jsonrpc":"2.0","method":"Add","params":{"a":100,"b":200}}{"id":101,"jsonrpc":"2.0","method":"Add","params":{"a":100,"b":200}}
    var r1 = ser.Deserialize(reader, typeof(JsonRpcRequest));
    // r1 holds first Request
    // But stream.Position is already 136
    var r2 = ser.Deserialize(reader, typeof(JsonRpcRequest));
    // r2 is null !!!???
}

答案 1 :(得分:0)

我接受了您的最初陈述和想法,并对此表示赞同。

您遇到的问题是,您试图将一个巨大的字符串传递给javascript函数,但是您无法真正控制字符串中要包含的内容,所以事情变得很棘手。

在创建javascript onClick代码时,我传递了javascript变量而不是整个字符串。我在html的开头设置了该变量的值,因此当他们单击它时该变量将可用。

检查一下:

<?php
//array for holding all articles 
$articles = array();

//the article in question
$article = new stdClass;
//id of the article
$article->id = 345;

//full text of the article
$article->fullText = "
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tempus, orci a lacinia ornare, magna ante tincidunt odio, a molestie velit libero sit amet massa. Nullam volutpat diam et tellus sodales cursus. Vestibulum tempor in eros vel tristique. Vestibulum varius purus in ultrices tincidunt. Morbi mi orci, faucibus vitae tempor sed, sollicitudin ut sem. Etiam porta sem justo, et dapibus ipsum accumsan sed. Suspendisse potenti. Vestibulum id turpis mattis, rutrum dui non, varius magna. Phasellus rhoncus auctor dapibus. Ut nunc erat, sodales eget consectetur nec, interdum sit amet libero. Cras eget dui ante. Aliquam sit amet nisl vitae libero posuere hendrerit. Aliquam porta at arcu nec sodales. Pellentesque sapien nisl, facilisis eget ornare id, convallis eget erat.
Nunc cursus porttitor aliquet. Mauris sapien nibh, fermentum in turpis in, ornare malesuada nulla. Aliquam varius turpis felis, non imperdiet ante ornare eu. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla eget viverra nisl. In nunc sapien, vehicula quis tristique commodo, congue eget felis. Vestibulum vehicula velit eros. Fusce nec neque sed leo ornare mollis ut vitae urna. Suspendisse vitae nisi ut nulla egestas gravida.
Integer et pretium ligula, vitae rutrum odio. Proin condimentum lectus et odio suscipit, ut pharetra justo luctus. Integer iaculis, tortor eu sodales volutpat, nibh nisi porttitor elit, et dapibus enim odio sed augue. Praesent nec turpis non mauris tincidunt interdum non in neque. Vestibulum sagittis leo magna, in malesuada dui viverra vel. Morbi ornare urna ac est pharetra, at ornare tortor ullamcorper. Pellentesque eget libero felis. Ut scelerisque nunc at pharetra ultricies. Nullam pretium sapien ex, at viverra ligula venenatis rutrum. Proin molestie hendrerit nunc non venenatis.
";
//short form of the article
if (str_word_count($article->fullText)>200){
    $article->shortText = implode(' ', array_slice(explode(' ', $article->fullText), 0, 100)).'...<input type="button" id="read" value="Read more" onclick="myFunction(\''.$article->id.'\',fullArticle_'.$article->id.');">';
}else{
    $article->shortText = $article->fullText;
}
//javascript code that needs to be run for each article
$article->javascriptVariable = 'var fullArticle_'.$article->id.' = `'. str_replace('`',"",$article->fullText) .'`;';
//save this article in our list of articles.
array_push($articles, $article);

?>
<!DOCTYPE html>
<html>
    <head>
        <title>Testing Speech thingy</title>
        <script>
            <?php 
                //set variables in the javascript to hold the full text
                foreach ($articles as $article){
                    echo $article->javascriptVariable . "\n";
                }
            ?>;

            function myFunction(article_id, article_full) { 
                var article_body = document.getElementById(article_id); 
                article_body.innerHTML = article_full;
            }
        </script>
    </head>
    <body>
        <?php
            foreach ($articles as $article){
                echo '<div class="article-excerpt">';
                echo $article->shortText;
                echo '</div>';
                echo '<div id="'.$article->id.'">';
                echo '</div>';
            }
        ?>
    </body>
</html>

另一个想法是将全文放在隐藏的div中,然后在单击时显示适当的div。这样做将避免需要通过javascript函数传递任何全文信息。唯一的缺点是Google搜索可能会因为内容重复而降低您的排名。

答案 2 :(得分:0)

PHP代码

function count_words_display($speech, $articleid){

 if (str_word_count($speech)>200){

    $speech_short = implode(' ', array_slice(explode(' ', $speech), 0, 100)).'...<input type="button" id="read" value="Read more" onclick="myFunction('.$articleid.')">';
        print "<div id = 'short".$articleid."'>".$speech_short."</div>";

        print "<div id = 'long".$articleid."' style='display:none'>".$speech."</div>";  
 }
 else{

    print $speech;
 }
}

JavaScript代码

function myFunction(article_id) {
 var x = document.getElementById('short'+article_id);
 var y = document.getElementById('long'+article_id);
 if (x.style.display === 'none') {
    x.style.display = 'block';
 } else {
    x.style.display = 'none';
   }

if (y.style.display === 'block') {
    y.style.display = 'none';
} else {
    y.style.display = 'block';
  }
}