2017-12-22 10 views
-1

私はconsole.logに値を表示することができましたが、WordPress REST APIから抽出した値をCSS背景画像を変更するために使用すると、定義されていない値。私は静的なHTMLを作成しようとしているが、自分のサイトにブログのおすすめ画像を表示しようとしている。WordPress REST API(JSON)でCSS背景画像を変更

JS:

var newImage; 
var postRequest = new XMLHttpRequest(); 
postRequest.open('GET','http://method.com.sg/post/wp-json/wp/v2/posts'); 
postRequest.onload = function(){ 
var ourData = JSON.parse(postRequest.responseText); 
newImage = ourData[0].better_featured_image.source_url; 

console.log(newImage); //Will output the hyperlink 
}; 
alert(newImage); // Output Undefined 
postRequest.send(); 

//Unable to work 
$('.container.withBg.post').css('background-image', 'url('+newImage+')'); 

答えて

1

アラートが()リクエストがロードされた後にのみ使用可能になりますが、警告が完了するまでにそのタスクを待ちませんし、実行するURLを必要としていないので、これがあるかもしれません時期尚早。 は、URLは以下のように利用可能になると呼ばれるBG画像の変更を処理するためにダミーの関数を作成してみてくださいすることができます

var newImage; 
var postRequest = new XMLHttpRequest(); 
postRequest.open('GET','http://method.com.sg/post/wp-json/wp/v2/posts'); 
postRequest.onload = function(){ 
var ourData = JSON.parse(postRequest.responseText); 
newImage = ourData[0].better_featured_image.source_url; 

console.log(newImage); //Will output the hyperlink 

//Make a function call here to change the background url 
change_background(newImage); 
}; 
postRequest.send(); 

function change_background(newImage){ 
    alert(newImage); // Output Undefined 
    $('.container.withBg.post').css('background-image', 'url('+newImage+')'); 
} 

あなたが好きに関数名を変更することができます。

+0

ああ動作します!ダミー関数は私の人生を救った。ありがとうございます。 –