2011-03-09 70 views
1

我想用我的輸入在我的文本框中使用jquery替換我的url中的參數。另外,我需要對輸入進行百分比編碼。我試圖使用jquery.validator.format,但它不工作。建議?在jQuery中格式化url

<script src="http://code.jquery.com/jquery-latest.js"></script> 
    <script src="http://jqueryjs.googlecode.com/svn/trunk/plugins/validate/jquery.validate.js"></script> 
<script language="javascript" type="text/javascript">  
$(document).ready(function() { 
     $("button").click(function() { 
      var str = "http://api.geonames.org/postalCodeSearchJSON?placename={0}&maxRows=10&username=<my username>"; 
      alert(str); 
      var loc = $("#location").val(); 
      alert(loc); 
      str = jQuery.validator.format(str, loc); 
      alert(str); 
     }); 
    }); 
+0

是的,我的意思是百分編碼 – rbur0425 2011-03-09 03:33:39

+0

替換字符串在哪裏(對於'placename'和'username')來自? – 2011-03-09 03:34:28

+0

他們來自文本框#位置和用戶名是硬編碼我只是沒有顯示它出於安全原因 – rbur0425 2011-03-09 03:38:33

回答

2

這應該只是正常工作,其中包括百分號編碼(通過encodeURIComponent()):

$("button").click(function() { 
    var str = "http://api.geonames.org/postalCodeSearchJSON?placename={0}&maxRows=10&username=redacted"; 
    var loc = encodeURIComponent($("#location").val()); 
    str = jQuery.validator.format(str, loc); 
    alert(str); 
}); 

的jsfiddle演示:http://jsfiddle.net/mattball/FFVCj/

0
$(document).ready(function() { 
    $("button").click(function() { 
    // var str = "http://api.geonames.org/postalCodeSearchJSON?placename={0}&maxRows=10&username=rbur0425"; 
    // alert(str); 
     var loc = $("#location").val(); 
    //  alert(loc); 
     // var loc2 = encodeURIComponent(loc); 
     var url = "http://api.geonames.org/postalCodeSearchJSON?placename=" + loc + "&maxRows=10&username=rbur0425"; 
//  alert(encodeURI(url)); 
    }); 
}); 

的作品對我好