[英]Properly setting up an Array from Wordpress REST API in javascript
This is a 2 part question: 这是一个两部分的问题:
1) I am trying to take these elements from WordPress' REST API and set them into an array ( map_locations
) which I've created. 1)我正在尝试从WordPress的REST API中获取这些元素,并将它们设置为我创建的数组(
map_locations
)。 Now, I've got the $.ajax
portion of the function working (meaning when I console.log it, I see [my_data]
, but the later half doesn't. 现在,该函数的
$.ajax
部分已经正常工作(意味着当我console.log它时,我看到[my_data]
,但后半部分没有。
map_locations.forEach( function( map_item ) {
console.log('hi');
}
I'm expecting the above to log to the console at least once, however I get nothing. 我期望以上内容至少一次登录到控制台,但是我什么也没得到。 The reason I have
console.log()
is just to see if I'm getting anything first. 我拥有
console.log()
的原因仅仅是为了看看我是否先得到了什么。 Is there something in my entire code that I have setup incorrectly? 整个代码中是否存在我设置不正确的内容? Is there a better way to do what I'm doing?
有没有更好的方式来做我在做的事情?
2) How do I access the data within the $.ajax
function for the media? 2)如何访问媒体的
$.ajax
函数中的数据? I have tried to use the following to set it, but I error out at ['0']
我尝试使用以下内容进行设置,但我在
['0']
处出错
image: post._embedded['wp:featuredmedia']['0'].media_details.sizes.thumbnail.
Full Code: 完整代码:
(function($) {
var map_locations = [];
// Works
$.ajax( {
url: '/wp-json/wp/v2/map-api?_embed',
method: 'GET',
success: function( data ) {
// Run through a foreach loop and setup the post data.
data.forEach( function( post ) {
map_locations.push( {
// Set fields
id: post.id,
title : post.title.rendered,
lat: post.acf.location_post_lat,
lng: post.acf.location_post_long,
content: post.content.rendered,
address: post.acf.address,
address2: post.acf.address2,
city: post.acf.city,
state: post.acf.state,
zip: post.acf.zip,
phone: post.acf.phone,
website: post.acf.website,
cat: post['map-cat'],
} )
} )
},
cache : false
} );
console.log( map_locations );
map_locations.forEach( function(post_item) {
console.log('hi');
} );
})(jQuery);
1) the reason which you're getting nothing in your function: 1)您的功能一无所获的原因:
map_locations.forEach( function(post_item) {
console.log('hi');
} );
is because you're calling the the map_locations
array before the promise has been resolved, in that case you could refactor your code and call inside the promise. 这是因为您在承诺未解决之前就调用了
map_locations
数组,在这种情况下,您可以重构代码并在map_locations
内部调用。
2) You're taking the zero in the second square parenthesis as string this must be a number, try this: 2)您将第二个圆括号中的零作为字符串,它必须是数字,请尝试以下操作:
image: post._embedded['wp:featuredmedia'][0].media_details.sizes.thumbnail.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.