如何在AngularJS控制器中编码URL

时间:2014-08-24 17:04:53

标签: javascript angularjs

尝试提交我在AngularJS控制器代码中动态构建的URL,然后使用encodeURIComponent()进行编码时,我遇到了一些问题

这是一个动态构建的URL示例(在编码之前,不会通过Fiddler提交):

http://localhost:49479/api/aggr?sid=f68f52614800393fdbef22cc55a7d3d0fea10e655fff6e7573ca&kri=[CDSStress A]:[USD 10Y X -1.25],[CDSStress A]:[USD 1Y X 1.25]&aggrFunc=SUM([CDSStress A]:[USD 10Y X -1.25]),SUM([CDSStress A]:[USD 1Y X 1.25])&dim=Counterparty

相同的网址,使用%20手动编码(通过Fiddler提交给API图层):

http://localhost:49479/api/aggr?sid=f68f52614800393fdbef22cc55a7d3d0fea10e655fff6e7573ca&kri=[CDSStress%20A]:[USD%201Y%20X%201.25],[CDSStress%20A]:[USD%201Y%20X%20-1.25]&aggrFunc=SUM([CDSStress%20A]:[USD%201Y%20X%201.25]),SUM([CDSStress%20A]:[USD%201Y%20X%20-1.25])&dim=Counterparty

但是,通过encodeURIComponent()进行编码不会通过Fiddler提交给我的API层。这是编码的网址:

http%3A%2F%2Flocalhost%3A49479%2Fapi%2Faggr%3Fsid%3Df68f52614800393fdbef22cc55a7d3d0fea10e655fff6e7573ca%26kri%3D%5BCDSStress%20A%5D%3A%5BUSD%201Y%20X%201.25%5D%2C%5BCDSStress%20A%5D%3A%5BUSD%201Y%20X%20-1.25%5D%26aggrFunc%3DSUM(%5BCDSStress%20A%5D%3A%5BUSD%201Y%20X%201.25%5D)%2CSUM(%5BCDSStress%20A%5D%3A%5BUSD%201Y%20X%20-1.25%5D)%26dim%3DCounterparty

和我的角度控制器代码,它构建了URL并提交给datacontext层:

function sendAggrRequest(kriList, aggrFunc, dim) {

        var results = [];
        var rageVars = $rootScope.rageSessionVars;
        var url = "http://" + rageVars.domainName + ":" + rageVars.port + "/api/aggr?sid=" + rageVars.sessionID +
                "&kri=" + kriList + "&aggrFunc=" + aggrFunc + "&dim=" + dim;            

        url="http://localhost:49479/api/aggr?sid=a74b9822cf5e0e75b0d8ff0c25981a573606893150348d6cad80&kri=[CDSStress%20A]:[USD%201Y%20X%201.25],[CDSStress%20A]:[USD%201Y%20X%20-1.25]&aggrFunc=SUM([CDSStress%20A]:[USD%201Y%20X%201.25]),SUM([CDSStress%20A]:[USD%201Y%20X%20-1.25])&dim=Counterparty"
        datacontext.sendAggrRequestToServer(encodeURIComponent(url)).then(function (data) {
            if (data.status == 'FAIL') {
                if (data.messages.length > 0) {
                    logErr("Error retrieving KRI list: " + data.messages[0]);
                    return;
                }
            }
            else {
                results = data.data;
            }                
        });
 }

如果您可以就编码网址的最佳方式提供一些建议,那就太棒了。

谢谢。

鲍勃

2 个答案:

答案 0 :(得分:0)

尝试

encodeURI(uri)? 

或者您可以使用regex replace

space %20

答案 1 :(得分:0)

我在AngularJS内使用encodeURIComponent时没有任何问题:

var params = $location.search();
var someThingEncoded = encodeURIComponent(params.someThing);

如果事情很时髦,您可能还想尝试$ log.log。例如,encodeURI可能不适用于url段,但encodeURIComponent仍然可能,因此您可以尝试同时登录到控制台和进行比较。