How to properly escape html sent as data in jQuery's .ajax function

走远了吗. 提交于 2019-12-29 01:34:51

问题


UPDATE: Once I looked at the problem in Firebug, I found my mistake immediately. And it was an embarrassing unmatched double quote that I must have deleted somehow. I had been using Chrome's developer window. Very sorry for using up your resources. But, lesson learned! ("I hope.)

What is the best way for me to escape html characters that I want to send to my server? I am using jQuery, .ajax(), and jsonp.

I'm writing a bookmarklet which sends parts of the current page's html to my server. Here is the ajax call:

jQuery.ajax({
    url: 'http://www.my_server.com/file.php?callback=?',
    dataType: 'jsonp',
    data: { someHtml: escape(jQuery(this).html().substring(0,1000)) },
    success: function() { // stuff },
    beforeSend: function(xhr) {
                  xhr.setRequestHeader('Content-type','text/html');
                },
    error: function() { // stuff }
});

I need to use JSONP and therefore I can't use POST, and this is why I'm truncating the html data. Things work if the html is "nice", but if it contains characters javascript doesn't like, then I have problems. I fixed my ' problem by using escape(), but now I think I'm having newline and tab problems.

Chrome's dev console gives me the same error:

Uncaught SyntaxError: Unexpected token <

which I assume means some character is causing things to break out of javascript. I have tried the following: escape(), encodeURI/Component(), serialize(), text(), but nothing has worked yet. At first, I didn't use beforeSend, but thought I should try it, but no difference.

Currently, I'm stuck with some html which has a line break, then a tab, then a couple of spaces. I have tried replacing these characters using replace():

... .substring(0,1000).replace(/(\r\n|[\r\n])/g,'')

I found this regex string on another site which is supposed to replace various combinations of carriage returns and line feeds.

I hope I've explained myself clearly enough. It's my first question at Stack Overflow so go easy on me. :)


回答1:


You don't need to escape or encode. jQuery will take care of properly URL encoding the data:

data: { someHtml: $(this).html().substring(0, 1000) },


来源:https://stackoverflow.com/questions/4122298/how-to-properly-escape-html-sent-as-data-in-jquerys-ajax-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!