2

我有一个json包含大约 20 个对象的文件,如下所示:

{
"firstName": "User1",
"lastName" : "UserLname",
"title": "Human",
"description": "Something Facinating",
"photoURL": "http://www.example.com/wp-content/themes/mytheme/images/profile/user1.jpg",
"contact": {
     "email" : "user1@example.com"
      }
}

我有一个 javascript 代码来将这些对象的图像/描述显示到页面。我希望这个网站可以上传到多个地方。json所以在这个文件中使用绝对 url 对我来说没有意义。我通过从文件中js传递一个变量并在 javascript 文件中调用它来克服这个问题。templateUrlheader.php

<script type="text/javascript"> 
    var templateUrl = '<?= get_bloginfo("template_url"); ?>';
</script>

在javascript中:$.getJSON(templateUrl+"/scripts/file.json", function(file){....}

我也想要一种将这个templateUrl变量传递给json文件的方法。因此,我可以将图像路径设置为 just images/profile/user1.jpg,并且可以根据网站的上传位置将 url 添加到此。

4

1 回答 1

1
#json.php
{
"firstName": "User1",
"lastName" : "UserLname",
"title": "Human",
"description": "Something Facinating",
"photoURL": "<?= $_GET['var']; ?>/images/profile/user1.jpg",
"contact": {
     "email" : "user1@example.com"
      }
}

 

#main page
<script type="text/javascript">
var templateUrl = encodeURI("http://example.com");

$(function(){
    $.getJSON(
        'json.php?var=' + templateUrl,

        function(data){
            $.each(data, function(key, val){
                console.log(key + ": " + val);
            });
        }
    );
});

</script>

 

Output:

firstName: User1
lastName: UserLname
title: Human
description: Something Facinating
photoURL: http://example.com/images/profile/user1.jpg
contact: [object Object]
于 2013-07-02T14:43:28.307 回答