2017-12-22 3 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

아! 거짓 기능으로 제 목숨을 구했습니다. @yamu Yamu 감사합니다. –