开发者

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:

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:

$Comme开发者_开发百科nt = 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!


Use encodeURIComponent

commReq.open("GET", '/receiveComment.php?com='+encodeURIComponent(Comment)+'&' + Math.random(), true);

You'll still need to encode for POST (credit to 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. 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜