背景:
我需要从json文件下面的路径获取图像:
{
"path" : " shape\/",
"info" : {
"author" : ""
},
"name" : "shape",
"layers" : [
{
"height" : 612,
"layers" : [
{
"name" : "bg_rectangle_1"
},
{
"height" : 475,
"layers" : [
{
"src" : "http://sitename.com/images/oneheart.png",
"name" : "mask_image_1"
},
{
"name" : "useradd_ellipse1"
}
],
"name" : "user_image_1"
}
],
"name" : "loveshape_17"
}
]
}
我成功完成了以下代码:
var maskedImageUrla = "";
$.getJSON('test.json', function(json) {
for (let layer of json.layers) {
if (layer.layers && layer.layers.length > 0) {
for (let temp of layer.layers) {
if (temp.src) maskedImageUrla = temp.src;
else if (temp.layers) {
for (let tl of temp.layers)
if (tl.src) maskedImageUrla = tl.src;
}
}
}
}
要求:
在上面的json文件中,如果src是这样的:"src" : "oneheart.png"
[而不是完整路径],那么如何获取图像呢?因为此路径中存在图片:http://sitename.com/images/oneheart.png
答案 0 :(得分:3)
您可以更改
if (tl.src) maskedImageUrla = tl.src;
对此
if(tl.src.includes('/')){
maskedImageUrla = tl.src
} else {
maskedImageUrla = `http://sitename.com/images/${tl.src}`
}
答案 1 :(得分:1)
var str = 'http://sitename.com/images/oneheart.png';
var strCopy = str.substring(str.lastIndexOf('/') + 1, str.length);
console.log(strCopy);
console.log('http://sitename.com/images/' + strCopy);
答案 2 :(得分:1)
您可以使用navigator.location.origin属性并在运行时连接字符串。例如:
var maskedImageUrla = "";
$.getJSON('test.json', function(json) {
for (let layer of json.layers) {
if (layer.layers && layer.layers.length > 0) {
for (let temp of layer.layers) {
if (temp.src) {
maskedImageUrla = navigator.location.origin + '/images/' + temp.src;
}
else if (temp.layers) {
for (let tl of temp.layers)
if (tl.src) maskedImageUrla = tl.src;
}
}
}
}
答案 3 :(得分:0)
我没有将前缀添加到t1.src
中,而是将前缀添加到temp.src
中,因此它不起作用.....以下解决方案对我有用
var maskedImageUrla = "";
$.getJSON('test.json', function(json) {
for (let layer of json.layers) {
if (layer.layers && layer.layers.length > 0) {
for (let temp of layer.layers) {
if (temp.src) maskedImageUrla = temp.src;
else if (temp.layers) {
for (let tl of temp.layers)
if (tl.src) maskedImageUrla = 'http://sitename.com/images/' + tl.src;
}
}
}
}