开发者

jQuery ajax call containing script-tag in data

开发者 https://www.devze.com 2022-12-13 02:34 出处:网络
I read some values from text boxes and send them via jQuerys post method to an server. If the user enters text containing something like \"blabla\", the call fails. The data looks like this in that ca

I read some values from text boxes and send them via jQuerys post method to an server. If the user enters text containing something like "bla bla", the call fails. The data looks like this in that case:

var data = { myKey: 'bla <script> bla' };开发者_如何转开发

And I send it to the server like this:

 $.post(targetUrl, data, function(x) {...});

On the server side (an Asp.Net web form) it looks like the call never reaches the server. Any hint how to solve that? If there's a convenient function which cleans data from bad tags, that would be fine too.


Have you desactivate the validate request of your aspx page?

add this in your page declaration: validateRequest="false"


To strip tags using a jQuery function:

jQuery.fn.stripTags = function() {
        return this.replaceWith( this.html().replace(/<\/?[^>]+>/gi, '') );
};

Do you receive a page_load in ASP.NET? If yes, isn't there anything in Request.Params?


I would suggest escaping your values client side using the javascript escape function as shown below

var data = { myKey: escape('bla <script> bla') };

Once you have done that, you can retrieve the correct value on the server side using the following (.Net Code)

HttpUtility.UrlDecode(param_value_to_decode)

I tested this and the correct value is being passed correctly to the server via the post request.

Hope this helps.

Additional Info : I forgot to mention the cause of the error. When inspecting the request using firebug, it returns a "500 Internal Server Error - A potentially dangerous Request.Form value was detected from...". This is a built in protection mechanism from asp.net to protect against script injection. The following page directive ValidateRequest="false" did not solve the problem as expected (Works in traditional WebForms). It might be something specific to the Mvc platform, not to sure. The above solution does work, so just use that.

Regards

G

0

精彩评论

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