繁体   English   中英

用jQuery发布textarea的值

[英]Posting the value of a textarea with jquery

我正在寻找一种使用javascript,jQuery和php读写Linux文本文件的(正确)方法。 具体来说,我想使用jQuery($(“#taFile”)。val();)来获取(#taFile)的值,然后将$ .post放入php脚本,该脚本随后将发布的值写入文本文件。

虽然我的代码大部分都能正常工作,但我遇到了一个麻烦:在获取textarea的值并将$。张贴到它时,所有特殊字符都将丢失。 具体来说,1)所有特殊字符都丢失,2)新行转换为空格,3)某些特殊字符(我注意到它与#一起丢失)之后的所有字符。

这些仍然是脚本的草稿,但是我非常欢迎任何改进和建议!

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代码无法显示。 并非某些脚本用于在更改选项卡时首先读取文件。 一切正常。

谢谢!

您可能想查看PHP htmlentitieshtmlspecialcharacters

注意:您正在使用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是正确的特殊字符

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM