2013-08-23 77 views
0

我在common.js文件中有以下代碼。如何使用`&`登錄jquery代碼來解析Url?

如果數據不匹配,則邏輯爲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) { } 
    }); 
} 

回答

1

試試這個

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

encodeURIComponent方法 Thisfunction編碼URI組件。

該函數對特殊字符進行編碼。另外,它編碼 以下字符:,/? :@ & = + $#

+0

非常感謝了解我:)工作很好 – Neo

+1

@ashuthinks很高興爲您效勞。無論何時我們要進行Web服務或Web通話,**編碼**都是必需的。我也在'C#'中遇到類似的問題,其中HttpUtility.UrlEncode出現了。所以請記住** URI編碼是強制性的** :) – Praveen

+0

您應該只編碼'name'不要編碼非動態的部分 –

0

您需要使用&方法encodeURIComponent()追加到參數字符串之前逃跑的參數值。

encodeURIComponent('name = My & Son')