jquery内容不在html表中显示

时间:2018-01-30 13:54:02

标签: javascript php jquery html

在我的php页面中,我正在查询数据库表,结果以html表格式显示。 数据库表的一个字段包含<script>代码和注释行以及其他代码。例如:

<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>

未显示包含jquery内容的<td>的数据。我在此jsfiddle中添加了代码。

任何人都可以帮我解决这个问题吗?提前谢谢。

2 个答案:

答案 0 :(得分:1)

使用htmlentities()页面

中的PHP功能

使用:

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

链接:https://www.w3schools.com/php/func_string_htmlentities.asp

答案 1 :(得分:0)

如果您想显示代码而不是执行它,那么您需要对其进行HTML编码。无论用什么语言(PHP或JS,我猜),你用它来获取内容并在页面上显示它将提供一个功能来完成它。从本质上讲,这涉及将<替换为&lt;,将>替换为&gt;

最终结果应该是这样的:

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>