通过 php 文件替换多个字符串

Multiple string replacement through php file

这是我的功能,它通过按下按钮激活,发送两个输入 ID 以形成字符串:

var str = "headingText=" + $("#headingText").val() +
    "&centerText=" + $("#centerText").val();

$.ajax({
    url: "indexpdf.php",
    data: str,
    cache: false,
    success: function (result) {
        console.log("Success!");
    }
});

现在这是我的 indexpdf.php 文件:

<?
$headingText = trim(isset($_POST['headingText']) ? $_POST['headingText'] : '');
$centerText = trim(isset($_POST['centerText']) ? $_POST['centerText'] : '');

$initialpdf = file_get_contents('file_html.php');

$initialpdf = str_replace(array(
        '%headingText%',
        '%centertext%'
    ), array (
        $headingText,
        $centerText,
    ), $initialpdf);

$fp = fopen('file_html2.php','w');
file_put_contents('file_html2.php', $initialpdf);
?>

这里的目标是从第一页的输入中获取两个字符串,并用它们替换 "file_html.php" 中的所有“%headingText%”和“%centerText%”标签,最后将其另存为"file_html2.php".

文件保存正常,但字符串替换不起作用..

您的 ajax 调用未设置为任何方法。它会自动使用 $_GET。如果你想让它使用 $_POST,你可以做 shorthand:

使用 POST 获取的页面从不缓存,因此 jQuery.ajaxSetup() 中的缓存和 ifModified 选项对这些请求没有影响。

$.post("indexpdf.php", data: str,function (result) {
        console.log("Success!");
});

或者只需将 "method" 选项添加到 ajax

$.ajax({
    url: "indexpdf.php",
    data: str,
    method: "POST",
    cache: false,
    success: function (result) {
        console.log("Success!");
    }
});

$.ajax 默认使用 GET 方法。如果服务器端代码期望接收 POST 数据,那么您必须添加:

$.ajax({
method: "POST",
...
});

此外,如果您使用 file_put_contents(),则不需要 fopen()

不是传递查询字符串供所有人查看,而是传递一个 JSON 对象,如下所示:

        var jsonData = {}
        jsonData.headingText = $("#headingText").val();
        jsonData.centerText = $("#centerText").val();

        $.ajax({
            url: "indexpdf.php",
            data: jsonData,
            cache: false,
            success: function (result) {
                alert("Success!");
            }
        });

这样更干净、更安全。访问数据可以在 PHP 文件中保持不变。