简体   繁体   中英

jquery content not displaying in html table

In my php page, I'm querying a database table and the results are shown in an html table format. One field of the database table contains <script> codes and commented lines along with other code. For eg:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td> <!-- STORES html --> <!-- Start: Code --> <script type="text/javascript"> console.log("testing"); if ( $.inArray( 'apple', ["apple", "orange", "grapes"]) > -1 ) { // fruits console.log("found"); } // fruits </script> <!-- End: --> </td> <td>row2</td> </tr> </table> 

The data for the <td> which contains jquery content is not getting displayed. I've added the code in this jsfiddle .

Can anyone help me to fix this? Thanks in advance.

Use the htmlentities() function in PHP page

Use:

$myCode = "" //Your code from the database will be stored in this variable
echo htmlentities($myCode); //outputs the code on page instead of executing it

Link: https://www.w3schools.com/php/func_string_htmlentities.asp

If you want to display the code, rather than execute it, then you need to HTML-encode it. Whatever language (PHP or JS, I guess) you're using to fetch the content and display it on the page will provide a function to do it. Essentially this involves replacing < with &lt; and > with &gt; .

The end result should be like this:

 td { border: 1px solid black; padding: 5px; } table { border-collapse: collapse; } 
 <table> <tr> <td> &lt;!-- STORES html --&gt; &lt;!-- Start: Code --&gt; &lt;script type="text/javascript"&gt; console.log("testing"); if ( $.inArray( 'apple', ["apple", "orange", "grapes"]) > -1 ) { // fruits console.log("found"); } // fruits &lt;/script&gt; &lt;!-- End: --&gt; </td> <td>row2</td> </tr> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM