2010-10-03 77 views
0

我正在寻找一种(正确的)方式来读写使用javascript,jQuery和php的linux文本文件。具体来说,我想用jQuery($(“#taFile”)。val();)和$ .post将一个(#taFile)值添加到一个php脚本中,该脚本依次将发布的值写入文本文件。虽然我的代码主要工作,我遇到了一个障碍:当采取textarea的值和$ .posting它,所有特殊字符都丢失。具体来说,1)所有特殊字符丢失,2)新行被转换为空格,3)所有字符在某些特殊字符后(我注意到它发生了#)都丢失了。用jquery发布textarea的值

这些仍然是草稿的草稿,但我非常乐意接受任何改进和建议!

的Javascript:

 
$(document).ready(function() { 
$("input:button").button(); 
$("#tabs").tabs(); 

$("#tabs").tabs({ 
    select: function(event, ui) { // When a tab is selected 
    file = ui.panel.id; 
    console.log("js: file: "+file); 
    if (file == "items" || file == "groups" || file == "whitelist" || file == "users"){ // if file is valid 
    $("#taFile").remove(); // Remove any old textareas 
    $("#"+file).html(''); // Add a new textarea 
    $.post("/php/getFile.php?action=read&file="+file, function(data){ // Post with the current file 
    $("#taFile").val(data); // Put file into textarea 
    }); 
    } 
    } 
}); 

$("#btnSubmit").click(function() { 
    var newcfg = $("#taFile").val(); 
    alert(newcfg); // This shows that newcfg preserves the exact value of the textarea 
    console.log(newcfg); // As does this. 
    $.post("/php/getFile.php?action=write&file="+file+"&newcfg="+newcfg); // This shows new lines (\n ?) as " " (a space) and removes all special characters (! , # ; : etc) 
}); 
}); 

PHP:

 
$file = $_REQUEST['file']; 
$newcfg = $_REQUEST['newcfg']; 
$action = $_REQUEST['action']; 
$user = 'public'; 
$config = "/home/$user/mc/$file.txt"; 

if ($action == "read"){ 
    $oldcfg = file_get_contents($config); 
    echo $oldcfg; 
} else if ($action == "write") { #if writing 
    $fh = fopen($config, 'w') or die("Cant write to file"); #open file 
    fwrite($fh, $newcfg); #write file 
    fclose($fh); #close file 
} 

我不得不删除PHP标签,因为他们造成了实际的PHP代码显示不出来。并不是说某些脚本是在第一次阅读文件时,在更改制表符时。这一切都很好。

谢谢!

回答

0

注意:您正在使用jQuery.post()并将您的数据设置为$_GET parameters。它应该被称为像;

$.post("/php/getFile.php", { action: "write", file: file, newcfg: newcfg }, 
    function(data){ 
    alert("Data Loaded: " + data); 
    }); 

你可以保持您的生产线打破了这样的功能:

function splitter($content) { 
$content = str_replace(chr(10),'<br/>',$content); 
$content = str_replace("<br/><br/><br/><br/>","<br/><br/>",$content); 
return $content; 
} 
你运行像

$newcfg = splitter($newcfg); 

而且typoknig是正确abouit特殊字符

+0

正确使用邮政的方式正是我一直在寻找的。我不需要splitter函数,因为我正在读取和写入unix配置文件(其中
没有意义),所以我需要保留\ n而不是
。出于与上述相同的原因,我也不需要htmlentities或htmlspecialcharacters。谢谢! – Kyle 2010-10-03 14:16:40

+0

当您收到解决问题的答案时,您应该始终使用答案左侧的勾号接受答案。投票决不会错过任何一个。 – 2010-10-03 14:54:58

+0

感谢您的提示。我是新来的。我试图给你投票,但我没有足够的声望。 – Kyle 2010-10-03 15:09:11