开发者

How to send html content through ajax request?

I have a form with a textarea (tinymce) for input content. When I perform an ajax request, I got the error:

A potentially dangerous Request.Form value was detected from the client

Then I've tried something like

html.encodeURIComponent() or escape() but the error is still here

开发者_StackOverflow社区

HTML:

<form id="editForm" action="" method="post">
  <input type="text" id="title" name="title" />
  <textarea id="content" name="content"></textarea>
  <input type="button" id="submit" onclick="Submit();" />
</form>

Script (I use jQuery)

function Submit(){
 $.ajax({                
  url: 'ajax.aspx?type=addcontent&' + $('#editForm').serialize() + '&rnd=' + Math.random(),
  success: function(data) {
   alert('OK');
  }
 });
}

As soon as I press the submit button, the error appears. No ajax request is made. I've tried add ValidateRequest="false" to the aspx page but the problem is still here.

Any help is appreciated!


$.post('/foo', { htmlContent: '<someHtml/>' }, function(result) {
    alert('ok');
});

Now the error comes from the server side script which doesn't accept HTML. The ASP.NET engine will automatically drop any requests containing HTML. There are different ways of disabling this behavior at your own risk. One of it consists of adding the ValidateRequest="false" to the aspx @Page header.

<%@ Page Language="C#" AutoEventWireup="false" ValidateRequest="false" %>

If it is an ASP.NET MVC application you could decorate the controller action to which you are posting with the [ValidateInput(false)] attribute:

[HttpPost]
[ValidateInput(false)]
public ActionResult Foo()
{
    ...    
}

It is also important to note that if you are running .NET 4.0 you will need to add the following to your web.config:

<httpRuntime requestValidationMode="2.0" />


In my opinion, another valid-but-slow alternative is base64-encoding your HTML string. I used the base64 extension of jQuery:

var html = ...my html unsafe text...

var encodedHtml =  $.base64.encode(html);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜