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

Multiple string replacement through php file

本文关键字:字符串 替换 php 文件 通过      更新时间:2024-04-26

以下是我的函数,它通过按下一个按钮来激活,发送两个输入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%"answers"%centerText%"标记,然后最终将其保存为"file_html2.php"。

文件保存良好,但字符串替换不起作用。。

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

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

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

或者简单地将"方法"选项添加到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文件中访问数据可以保持不变。