doudiewen9435
doudiewen9435
2014-08-23 11:10

将the_content()存储到javascript / jquery变量中

How can I do that ? Store the_content() into a variable . What I've tried :

<script type="text/javascript">
    window.the_content = "<?php the_content(); ?>";
</script>

and this

<?php 
    ob_start();
    the_content();
    $content = ob_get_clean();
?>

<script type="text/javascript">
    window.the_content = "<?php echo $content; ?>";
</script>

The problem is that what's echo-ed it's a multi-line string and that can't be stored as a javascript variable. I tried to trim() chop() htmlentities_decode() the string but it's useless.

I know that there's a function <?php echo get_the_content(); ?>that take off the html tags but the spaces and line-breaks are still there. I want to be able to parse the_content() via jquery .

Copy paste of the output from Google Chrome Developer Tool :

                                window.the_content = "<h1>Welcome to dasqwe tsqwe dwemo site</h1>
<p>&nbsp;</p>
<p>asdioquwidqwd</p>
<p>qwdoqwkdpqkwdkoqpwodkqwodpqwd</p>
<p>qwdkpoqwkdpqwokdpqwokdpqwkdpqwodkq</p>
<p>wdqwodkqpowkdpqwkdpqwkdopqwkdoq</p>
<p>wdqkowpdkqwpokdpoqkwdpqowkdpoqwkdqwd</p>
<p><span id="more-13"></span></p>
<h1>Page 2</h1>
<p>qwiodjiqwjdqiowjdioqwjdiqwd</p>
<p>qwdjoqwijdoqiwjdioqwjiodjqwodjqowdijas</p>
<p>dqoijwdioqjwdoqjwiodjqwodjqwdjasdqwodijqowdjqiowjdoqjdoad</p>
<p>qwodiqwjdoiqwdijoqwdqwiqiodijoqwdjiqwq</p>
<p>&nbsp;</p>
";
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • duanlv1366 duanlv1366 7年前

    Try using json_encode, it should escape most of the characters that would make it break

    <?php
        ob_start();
        the_content();
        $data = ob_get_contents();        
        ob_end_clean();        
    ?>
    window.the_content = <?php echo json_encode($data); ?>;
    

    You could also just strip out the new lines

    window.the_content = "<?php str_replace("
    ","",the_content()); ?>";
    

    Note that you would have to do other stuff to make sure it doesnt break, for instance escape double quotes etc.

    点赞 评论 复制链接分享
  • dongzhankou2090 dongzhankou2090 7年前

    JSON Encoding on the PHP side and decoding on the Javascript side will handle this for you.

    <?php
        ob_start();
        the_content();
        $content = ob_get_clean();
    ?>
    <script type="text/javascript">
        window.the_content = <?php echo json_encode($content); ?>;
    </script>
    
    点赞 评论 复制链接分享
  • dongpu42006096 dongpu42006096 7年前

    Please replace all the linebreaks to <br/>:

    <script type="text/javascript">
      window.the_content = "<?php 
        ob_start();
        the_content();
        $content = ob_get_clean();
        echo str_replace("
    ","<br/>", str_replace("", "", $content));              
      ?>
    </script>
    

    And on the JS-side:

    $( '.content' ).the_content);
    
    点赞 评论 复制链接分享

相关推荐