在jQuery中,我们通常利用$.ajax或$.post进行数据传递处理,但这里通常不能传递特殊字符,如:“<”。本文就介绍如何传递这种含特殊字符的数据。

1、准备页面和控制端代码

页面代码如下:

<  type=\"text/ \">
  $(function() {
      $(\"#btnSet\").click(function() {
        var a = $(\"#txtValue\").val();
        var data = { Name: a };
        alert(data);
        $.ajax({
          url: \'@Url.Action(\"MyTest\")\',
          type: \'post\',
          dataType: \'json\',
          data: data,
        });
      });
    }
  );
</ >
<h2>Index</h2>
<input type=\"text\" id=\"txtValue\"/><input type=\"button\" value=\"设置\" id=\"btnSet\"/>

后台代码如下:

public ActionResult MyTest(StudentInfo stu)
{
    return Content(\"OK\");
}

其中StudentInfo定义如下:

public class StudentInfo
{
  public string Name { get; set; }
}

 

2、测试数据传递

当我们传递普通数据时,一切正常。

但当输入含特殊字符的数据时,不能正常传递到后台。

 

3、处理方法

如果确定要传递特殊字符,需要对jQuery代码作调整,调整后的请求代码如下:

<  type=\"text/ \">
  $(function() {
      $(\"#btnSet\").click(function() {
        var a = $(\"#txtValue\").val();
        var data = JSON.stringify({ Name: a });
        alert(data);
        $.ajax({
          url: \'@Url.Action(\"MyTest\")\',
          type: \'post\',
          dataType: \'json\',
          data: data,
          contentType: \'application/json\'
        });
      });
    }
  );
</ >

调整的地方主要有两点:

对要传递的json数据作序列化JSON.stringify
在$.ajax请求中新增参数:contentType:'application/json'

收藏 打印