通过PHP/AJAX发送HTML代码时会转义双引号

3

当我点击时,我会创建一个新的.html网页。我的HTML代码存储在名为content的变量中。但是最终,当页面被创建时,代码自动有“(它转义了双引号)。有没有办法让我做到这一点,使网页没有转义的双引号?

HTML代码:

<html>
<body>
<button onclick="makePage()">Generate Link</button>
<script src="makePage.js">
</script>
<script>
var img = document.getElementById("img").value;
var content = document.getElementById("content").value;

</script>

</body>
</html>

JAVASCRIPT代码:

function makePage(){

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
alert("webpage " + xmlhttp.responseText + " was successfully created!");
     }
     var content = '<html><head><meta name="twitter:card" content="summary_large_image"><meta name="twitter:site" content="@nytimes"><meta name="twitter:creator" content="@SarahMaslinNir"><meta name="twitter:title" content="Parade of Fans for Houston’s Funeral"><meta name="twitter:description" content="NEWARK - The guest list and parade of limousines with celebrities emerging from them seemed more suited to a red carpet event in Hollywood or New York than than a gritty stretch of Sussex Avenue near the former site of the James M. Baxter Terrace public housing project here."><meta name="twitter:image" content="http://graphics8.nytimes.com/images/2012/02/19/us/19whitney-span/19whitney-span-articleLarge.jpg"></head><body></body></html>';
xmlhttp.open("GET","http://ahansabharwal.com/makePage.php?content=" + content, true);
xmlhttp.send();
}

PHP 代码:

<?php
$content = $_GET["content"];
$file = "" . uniqid() . ".html";
file_put_contents($file, $content);
echo $file;
?>
1个回答

3

看起来PHP启用了magic_quotes_gpc(在后续版本中已被弃用)。如果是这种情况,您需要在处理之前调用stripslashes()函数来处理$_GET的值。

类似于:

<?php
$content = $_GET['content'];
if (get_magic_quotes_gpc()) {
     $content = stripslashes($content);
}

在发送GET请求之前,您还应该对content进行URL编码(JavaScript中的encodeURIComponent()方法)。但是,这个内容通过GET请求发送会很多,考虑改用POST请求。


好的,那么这应该是我的代码吗?: $content = stripslashes("content"); $content = $_GET["content"]; - KidCoder
好的,就像这样,我已经添加了一个代码示例。首先需要检查magic_quotes_gpc是否启用。在PHP的较新版本中,此设置未启用。您使用的是哪个版本的PHP? - MrWhite
在早期版本的PHP中,默认情况下启用了magic_quotes_gpc。是的,您可以在服务器上禁用此设置。但是,为了编写可移植的代码(如果更改服务器或在其他地方使用相同的代码),则至少需要检查并相应地处理它。这是PHP的不幸遗产,但是自PHP 5.4以来已完全删除。 - MrWhite

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接