如何使用`&`登录jquery代码解析Url?

时间:2013-08-23 05:10:38

标签: javascript jquery asp.net-mvc jquery-ui

我在common.js文件中有以下代码。

如果数据不匹配,则

逻辑为HighlightTextBox;如果数据匹配,则为RemoveHighlightTextBox

url  = /Services/GetAutoCompleteData?v=

name = My & Son

actualUrl = /Service/GetData?v=My & Son&eq=true

//debuge following js code and found above values
//here problem is because of `&` sign url gets disturb as `actualUrl is /Service/GetData?v=My & Son&eq=true`
//so after `&` sign url gets ignore by js (i.e Son&eq=true code)
//i have passes values `My & Son` but actually js parsing it as `My` so how do I parse my original URL with `&` sign ?

var div = $(this).closest("div");
var elem = div.find(":text");
elem.change();
var name = elem.val();
var actualUrl = url + name + "&eq=true"
var filter = $(this).attr("filter");
if (name == "") {
    div.find(":hidden").val('');
    return;
}
AjaxPostCall(actualUrl, filter, function (data) {
    if (data == null || data.length != 1) {
        HighlightTextBox(elem);
        div.find(":hidden").val('');
        return;
    }
    RemoveHighlightTextBox(elem)
    div.find(":hidden").val(data[0].Key);
    elem.val(data[0].Value);
});

function AjaxPostCall(actualUrl, extraParam, onSuccess) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: actualUrl, 
        data: extraParam,
        dataType: "json",
        success: function (data) { if (onSuccess != null) onSuccess(data); },
        error: function (result) { }
    });
}

2 个答案:

答案 0 :(得分:1)

试试这个

  var actualUrl = encodeURIComponent(url + name + "&eq=true");
  

encodeURIComponent 此功能对URI组件进行编码。

     

此功能可对特殊字符进行编码。另外,它编码了   以下字符:,/? :@& = + $#

答案 1 :(得分:0)

在附加参数字符串之前,您需要使用方法encodeURIComponent()使用&转义参数值。

encodeURIComponent('name = My & Son')