如何在wordpress循环中获取json?

时间:2014-08-21 17:42:25

标签: jquery ajax json wordpress last.fm

如何在wordpress循环中获取json? 现在我有了它并且它工作正常,但非常慢:

<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
<?php $title = $post->post_title;
$context = stream_context_create(array('http' => array('ignore_errors' => true)));
if ($request = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=2b35547bd5675d8ecb2b911ee9901f59&artist='.urlencode($title).'', false, $context)) {
$xml = new SimpleXMLElement($request);?>
<img src="<?php if($xml->artist->image[3] != '') { echo $xml->artist->image[3]; } else { echo '/another-image.png'; } ?>"> // output image
<?php } endwhile;?>

现在我需要使用ajax而不是xml来获取图片网址,我已经请求过类似的内容。 如何在循环中插入此ajax输出?有人能帮助我吗?

$.ajax({
url: 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=<?php echo urlencode($title);?>&api_key=2b35547bd5675d8ecb2b911ee9901f59&format=json',
success: function(data) {

    if(data.artist.image[3]["#text"] != '') {
    // don't know how output data.artist.image[2]["#text"]
    } else {
    // output another image
    }
},
})

1 个答案:

答案 0 :(得分:0)

你现在遇到的问题是,你正试图在php中使用javascript解析的数据。您最好获取数据并仅在php中解析它。 以下是示例:

$request = file_get_contents( 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=' . urlencode($title) . '&api_key=2b35547bd5675d8ecb2b911ee9901f59&format=json' );
$json_decoded_request = json_decode( $request, TRUE ); // true in 2nd argument will turn the json object into array
if ( $json_decoded_request['artist']['image'][3]['#text'] != '' ) {
    // do what you want to do with image file fetched.
} else {
    // output another image.
} 

如果您想了解更多相关信息,请查看此网址:http://php.net/manual/en/function.json-decode.php