如何使用 ajax 通过 url 发布消息并仍然保留换行符?
这是 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);
}
}
现在接收评论的 php 页面 (receiveComment.php) 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')");
显然这些只是示例剪辑,但是从 2 页开始。页面 B 永远不会被看到,因为我使用 ajax 来存储评论。但我希望能够存储用户可以在文本区域框中插入的换行符。任何帮助或建议将不胜感激!
Here is a sample of the javascript/ajax on PAGE A:
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:
$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. Page B doesn't ever get seen since its through ajax that I'm using to store the comment. But I want to be able to store line breaks that a user may insert in the textarea box. Any help or recommendations would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
encodeURIComponent
您仍然需要对 POST 进行编码(归功于 agrothe)
Use
encodeURIComponent
You'll still need to encode for POST (credit to agrothe)
在 preg_replace() 函数调用中的第一个参数中,您正在搜索 \n 并将其替换为空。这很可能是问题的原因,因为 \n 代表换行符,因为它被双引号括起来。
我会尝试从 preg_replace() 函数中删除“\n”。
如果它是单引号,它不会将 \n 解释为换行符,而是将其视为其表面值。
仅供参考,通过 GET 传递信息不会去除 jQuery 中的换行符。在较旧的浏览器中,GET 确实将请求的 URL 限制为 255 个字符(尽管在 Firefox 1 和 IE 6 天之前),而 POST 支持无限大小。
Within your preg_replace() function call, within the first argument, you're searching for \n and replacing it with nothing. This is most likely the cause of your problem, as \n represents a linebreak because it is surrounded in double quotes.
I'd try removing "\n" from your preg_replace() function.
If it was a single quote, it would not interpret the \n as a line break, but would take it for its face value.
And FYI, passing information via GET does NOT strip out line breaks in 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.
使用 POST 而不是 GET。或者对 GET 方法的注释进行 URL 编码。
我认为如果你想保留换行符等,POST 会更好地为你服务。
Use POST instead of GET. Or URL encode the comment for the GET method.
I think POST would serve you better if you want to preserve line breaks and such.