如何通过URL传递带有对象值的参数

时间:2017-07-10 09:49:30

标签: javascript url parameters

我创建了一个允许将HTML转换为PDF的项目。我正在使用phantom-render-stream  将HTML转换为PDF。我现在的问题是,我无法将对象值传递给HTML。以下是我的代码。

app.js

var username = "AAA";
var pets = [
   {id: 1, name: "cat"},
   {id: 2, name: "dog"},
   {id: 3, name: "sugar glider"}
];
var address = {
    line1: "Street A123",
    town: "Edinburgh",
    country: "Scotland"
};

render('http://localhost:8888/createForm.html?username='+username+'&pets='+pets+'&address='+address
.pipe(fs.createWriteStream('customer.pdf'));

createForm.html中,我使用AngularJS获取并查看PDF的值。

createForm.html

<script>
        var app = angular.module('myApp', []);

        app.config(function($locationProvider){
            $locationProvider.html5Mode(true);
        });

        app.controller('getDataCtrl', function($scope, $location) {
                         var url = decodeURIComponent( $location.url() );
             var value = $location.search();

            $scope.username = value.username;
            $scope.pets = value.pets;
                       $scope.address = value.address;
            })
</script>

<body>
      <div ng-app="onePayForm" ng-controller="getDataCtrl">
           <p>{{username}}</p>
           <p>{{pets[0].name}}</p>
           <p>{{address.line1}}</p>
      </div>
</body>

成功将HTML转换为PDF后,我打开了pdf文件以查看结果。只有用户名显示在pdf中,其余的显示为{{pets[0].name}} {{address.line1}}

1 个答案:

答案 0 :(得分:2)

var readyPets = encodeURIComponent(JSON.stringify(pets));
var readyAddress = encodeURIComponent(JSON.stringify(address));

您的查询参数需要在将它们附加到网址之前准备好。你应该做什么

render('http://localhost:8888/createForm.htmlusername='+username+'&pets='+readyPets+'&address='+readyAddress)
        .pipe(fs.createWriteStream('customer.pdf'));

然后将上面的代码更改为:

$scope.pets = JSON.parse(decodeURIComponent(value.pets));
$scope.address = JSON.parse(decodeURIComponent(value.address));
在createForm.html中解析这些参数查询:

Compagny