在jquery中,我们通常利用$.ajax或$.post进行数据传递处理,但这里通常不能传递特殊字符,如:“
1、准备页面和控制端代码
页面代码如下:
<script type="text/javascript"> $(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, }); }); } ); </script> <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代码作调整,调整后的请求代码如下:
<script type="text/javascript"> $(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' }); }); } ); </script>
调整的地方主要有两点:
对要传递的json数据作序列化JSON.stringify
在$.ajax请求中新增参数:contentType:'application/json'
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号