如何使用jQuery发送包含特殊字符的查询字符串数据?

时间:2016-03-09 07:55:38

标签: javascript jquery

当我向我的ASP.Net MVC控制器发送数据(字符串值)时,数据发送成功。当我发送特殊字符时,例如.&,会显示如下错误:

  

HTTP 404.您要查找的资源(或其中一个依赖项)可能已被删除,名称已更改或暂时不可用。请查看以下网址,并确保拼写正确)

为什么会这样?我无法找到解决方案。请帮我解决这个问题。

$(function() {
    var link = '@Url.Action("Index", "Home", new {id= "_Description_"})';
    $('#btnSaveComments').click(function() {
        var description = $('#descr').val();           
        $('#btnSaveComments').attr('href', link.replace('_Description_', description));
    });
});
@Html.TextAreaFor(model => model.Description, new { id = "descr" })              
<button type="submit" text="submit" id="btnSaveComments" />                  
public ActionResult Index(string id)
{
    return view();
}                                                       

2 个答案:

答案 0 :(得分:1)

您需要对字符串进行编码,您可以使用encodeURIComponent

进行编码
$('#btnSaveComments').attr('href', link.replace('_Description_', encodeURIComponent(description)));

但请注意,href属性在button元素上无效。相信您可能希望设置action的{​​{1}}属性。无论哪种方式,逻辑都是一样的。

答案 1 :(得分:0)

在Url中发送特殊字符时,我收到了同样的错误消息。您需要正确编码url字符串。封装在encodeURIComponent

var description = encodeURIComponent($('#descr').val());