如何?通过jQuery.ajax从PostMirror编辑器发送PHP代码:POST并使用php:file_put_contents();

时间:2012-03-03 03:40:19

标签: php jquery codemirror

我正在制作http://c9.io类似的服务,可以直接在浏览器上编辑我的服务器上的.php文件。

我在那里实现了CodeMirror编辑器。 编辑看起来如下:http://codemirror.net/mode/php/index.html

我的问题是我无法通过jQuery.ajax POST发送包含php代码的数据。

让我们想象一下,我想将以下行保存到hello.php:

 <?php 
         require_once("lukujA.php"); 
 ?>

我使用以下js / jquery代码来保存文件:

$(".save-file").click(function (){
            var content = editor.getValue(); //textarea text
            var path = "hello.php";
        //following line shows content-data as it shows on CodeMirror editor
        //confirm box without any quotes / slashes / and with every linebreak

            var response = confirm("Do you want to save? DATA: " + content);
            if(response)
            {
                $.ajax({
                    type: "GET",
                    url: "saveFile.php",
                    data: "content="+content+"&path="+path+"",
                    success: function(){
                        alert("File saved!"); 
                    }
                });
            }
            else{
                alert("File not saved!");
            }
        });

saveFile.php:

$path = $_GET['path'];
$content = $_GET['content'];

if($path !== "" and is_writable($path))
    file_put_contents($path, $content);

上面的代码输出hello.php,如下所示(在一行和斜杠上)(使用POST似乎删除了我在编辑器上创建的任何换行符):

<?php require_once(\"lukujA.php\"); ?>

我无法在saveFile.php上使用stripslashes($content);,因为我有以下PHP代码:

<?php echo "<input type=\"text\" name=\"foo\">"; ?>

strip_slashes将删除这些斜杠,代码在执行时将变为无效。

我应该如何看待这个以及如何将新代码保存到文件中? 你会怎么做这种编辑?

由于

1 个答案:

答案 0 :(得分:3)

完成以下工作:

    $(".save-file").click(function (){
        editor.save();
        var content = editor.getValue(); //textarea text
        var path = $("#hiddenFilePath").text(); //path of the file to save
        var response = confirm("Do you want to save?");
        if(response)
        {
            $.ajax({
                type: "POST",
                url: "saveFile.php",
                data: {c:content,p:path},
                dataType: 'text',
                success: function(){
                    alert("File saved!"); 
                }
            });
        }
        else{
            alert("File not saved!");
        }
    });

请参阅代码data: {c:content,p:path}, dataType: 'text',

并且在saveFile.php中我使用stripslashes($content)因为我似乎在php设置上有魔术引号。

当我需要发送像echo "<br><a href=\"?p=$p&vko=$vkoPrev\">Edellinen</a> <a href=\"?p=$p&vko=$vko\">Tämä viikko</a> <a href=\"?p=$p&vko=$vkoNext\">Seuraava</a><br><br>";这样的数据时,如果我通过POST发送数据,那么在我的数据引号之前仍会保留这些斜线,就像上面所见urlEncoding在我的数据斜线之前添加斜杠一样。

很难解释。希望将来有人能从中得到一些东西:)对不起英语不太好。