2014-01-18 104 views
0

我在通過(HTML格式表單提交)到(在PHP中回顯)中處理(通過JavaScript生成)字符串時遇到一些奇怪的行爲。代:PHP或HTML格式搞亂字符串格式化

function constructCanvasString(){     

    //<table> added later, when title and artist name is available. 
    var canvasString = ''; 

    for (var y = 0; y < height; y++) { 
     canvasString += "<tr>"; 
     for (var x = 0; x < width; x++) { 
      canvasString += "<td x='" + x + "' y='" + y + "' style='background-color: " + $("#" + x + "-" + y).css('background-color') + "'></td>"; 
     } 
     canvasString += "</tr>"; 
    }  
    canvasString += "</table>"; 
    console.log(canvasString); 
    document.getElementById('canvasstring').value = canvasString; 
} 

console.log(canvasString);返回代碼,其中td看起來像這樣:

<td x='23' y='4' style='background-color: rgb(0, 0, 255)'></td> 
<td x='24' y='4' style='background-color: transparent'></td> 

該字符串被賦予一個表單字段。該形式如下:

<form id="publishform" method="POST" action="publish-canvas.php"> 
     <input type="text" name="title" value="Title"> by 
     <input type="text" name="artist" value="Artist"> 
     <input type='hidden' id="canvasstring" name='canvasstring' value=''> 
     <input type="submit" id="publishbutton" value="Publish"> 
</form> 

形式信息隨後被傳遞到發佈 - canvas.php持有這樣的代碼:

<?php 

$title = $_POST['title']; 
$artist = $_POST['artist']; 
$canvasstring = $_POST['canvasstring']; 
$canvasstring = "<table id=\"" . $title . "_by_" . $artist . "\" title=\"" . $title . "_by_" . $artist . "\">" . $canvasstring; 
echo $canvasstring; 

?> 

在該頁面中,TD的這個樣子的,搞亂了我仔細格式化:

<td transparent\'="" style="\'background-color:" y="\'0\'" x="\'2\'"></td> 
<td 0)\'="" 255,="" rgb(255,="" style="\'background-color:" y="\'0\'" x="\'3\'"></td> 

這是怎麼回事,我該如何阻止它?

回答

0

我會說在第一步,當你在javascript中生成html並將其放入輸入框時,問題發生。你在你的輸入框中輸入了真實的 - 未轉義的html,這會弄亂頁面的html。你看到的結果可能是瀏覽器試圖糾正它。

您需要在javascript函數中生成轉義html,並將其放入您的輸入框中。因此,沒有<人物,而是一個&lt;,沒有>&gt;

你可以在你的JavaScript直接更改,或者您可以使用function from an answer here on SO