【问题标题】:Textarea - missing new lineTextarea - 缺少新行
【发布时间】:2014-04-03 18:41:56
【问题描述】:

我有以下代码:

<form action="../p/padd.php" method="POST"> 
<input type="button" value="Náhľad"  OnClick="javascript:nahlad()" /> 
<textarea tabindex="4" id="textra" name="text" ></textarea>
<input type="submit" value="Vložiť" /> 
</form>

<span id="nahlad"> </span>

<script>
   function nahlad()
   {
     var textra = document.getElementById("textra").value;
     alert (textra);
     var xmlhttp;
     if (window.XMLHttpRequest) {xmlhttp=new XMLHttpRequest();
   }
   else
     {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
   xmlhttp.onreadystatechange=function()
   {
   if (xmlhttp.readyState==4 && xmlhttp.status==200) 
   {
     document.getElementById('nahlad').innerHTML = xmlhttp.responseText;
   }
  }
xmlhttp.open("GET","ssnahlad.php?text=" + textra,true);
xmlhttp.send();
}
</script>

当我在 textarea 中输入以下内容时(是的,输入时有“新行”)

asd
asd

然后点击 Nahlad 按钮

ssnahlad.php 包含

<?php
$new = $_GET['text'];
echo nl2br($new);
?>

那么为什么 id=nahlad 的 span 包含

asdasd 

而不是

asd
asd  

【问题讨论】:

  • 在使用 ajax 发送之前,您可能需要对其进行编码。你可以在发送之前提醒 textra 的值,看看你得到了什么,可能是“asdasd”
  • 警报(文本);工作正常。没有问题
  • 包含$_GET['text']; 换行符号\r\n\n 或类似的或仅包含asdasd??尝试使用var_dump() 进行检查
  • 字符串“asdasd”(长度=6)

标签: javascript php html textarea newline


【解决方案1】:

现在我在家并且可以测试,这将起作用:

  var newText = encodeURIComponent(textra);

在发送之前使用encodeURIComponent 将正确呈现您的输出,而在服务器端没有解码

【讨论】:

  • 你这样做的原因是什么?
  • 我有 textra,用户在其中输入文本,我向他展示它在页面上的外观,我也需要使用新行,对于某些用户来说,很难记住 html 代码来创建新行...这只是代码的一部分,但有错误
  • 谢谢,抱歉耽搁了一段时间;我讨厌试图用手机回答问题。一旦我回到家,它就变得很容易修复。
猜你喜欢
  • 1970-01-01
  • 2018-09-01
  • 2017-07-26
  • 2014-10-12
  • 2014-03-05
  • 1970-01-01
  • 1970-01-01
  • 2016-01-29
  • 2014-06-11
相关资源
最近更新 更多