[英]How can I use ajax to post message through a url and still keep line breaks?
Here is a sample of the javascript/ajax on PAGE A: 以下是PAGE A上的javascript / ajax示例:
var commReq = getXmlHttpRequestObject();
function AddComment(Comment){
if (commReq.readyState == 4 || commReq.readyState == 0){
commReq.open("GET", '/receiveComment.php?com='+Comment+'&' + Math.random(), true);
commReq.onreadystatechange = handleComment;
commReq.send(null);
}
}
Now the php page that receives the comment (receiveComment.php) PAGE B: 现在收到评论的php页面(receiveComment.php)PAGE B:
$Comment = mysql_real_escape_string(preg_replace("/[^A-Za-z0-9_,.!@:'\"\/\n ]/","", $_GET['com']));
mysql_query("INSERT INTO Comments (Comment,Date) VALUES ('$Comment','$Date')");
Obviously these are just sample cuts but from 2 pages. 显然这些只是样本削减,但是从2页开始。 Page B doesn't ever get seen since its through ajax that I'm using to store the comment. 自从我通过ajax用于存储评论以来,页面B从未被人看到过。 But I want to be able to store line breaks that a user may insert in the textarea box. 但我希望能够存储用户可以在textarea框中插入的换行符。 Any help or recommendations would be greatly appreciated! 任何帮助或建议将不胜感激!
Use encodeURIComponent
使用encodeURIComponent
commReq.open("GET", '/receiveComment.php?com='+encodeURIComponent(Comment)+'&' + Math.random(), true);
You'll still need to encode for POST (credit to agrothe) 您仍然需要对POST进行编码(信用额度为agrothe)
commReq.open("POST", '/receiveComment.php?' + Math.random(), true);
commReq.onreadystatechange = handleComment;
commReq.setRequestHeader("Content-Type", "multipart/form-data");
commReq.send('com=' + encodeURIComponent(Comment));
Within your preg_replace() function call, within the first argument, you're searching for \\n and replacing it with nothing. 在preg_replace()函数调用中,在第一个参数中,您正在搜索\\ n并将其替换为空。 This is most likely the cause of your problem, as \\n represents a linebreak because it is surrounded in double quotes. 这很可能是导致问题的原因,因为\\ n表示换行符,因为它用双引号括起来。
I'd try removing "\\n" from your preg_replace() function. 我尝试从preg_replace()函数中删除“\\ n”。
If it was a single quote, it would not interpret the \\n as a line break, but would take it for its face value. 如果它是单引号,它不会将\\ n解释为换行符,而是将其作为其面值。
And FYI, passing information via GET does NOT strip out line breaks in jQuery. 而且,仅供参考,通过GET传递信息并不会消除jQuery中的换行符。 In older browsers, GET it does limit the URL being requested to 255 characters though (pre Firefox 1 and IE 6 days though) while POST supports an unlimited size. 在较旧的浏览器中,GET确实将请求的URL限制为255个字符(虽然Firefox 1和IE 6天之前),而POST支持无限大小。
Use POST instead of GET. 使用POST而不是GET。 Or URL encode the comment for the GET method. 或者URL编码GET方法的注释。
I think POST would serve you better if you want to preserve line breaks and such. 如果你想保留换行符等等,我认为POST会更好地为你服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.