我使用Wikipedia API来提取和显示有关主题的信息。
我的代码适用于单个主题:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page=Dementia&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
var markup = data.parse.text["*"];
var i = $('<div></div>').html(markup);
// remove links as they will not work
i.find('a').each(function() { $(this).replaceWith($(this).html()); });
// remove any references
i.find('sup').remove();
// remove cite error
i.find('.mw-ext-cite-error').remove();
$('#article').html($(i).find('p'));
},
error: function (errorMessage) {
}
});
});
<div id="article"></div>
在上面的代码中,主题是&#34;老年痴呆症&#34;显示:
&page=Dementia
上面的代码适用于SINGLE主题,但现在我想修改它以循环ARRAY主题,并使用&#34; wikipedia_page_url&#34;数组中每个主题的值,以确定要拉出的页面,然后输出页面上每个主题的内容:
<?php foreach ($resident_conditions as $resident_condition) { ?>
<?php
$condition_id = $resident_condition['condition_id'];
$condition = sw::shared()->conditions->getForID($condition_id);
$wikipedia_page_url = $condition['wikipedia_page_url'];
?>
<h6><?php echo $condition['condition_name']; ?></h6>
<div id="<?php echo $condition['condition_name']; ?>">
<!-- This is where I want to place the content pulled from Wikipedia for each topic -->
</div>
<?php } ?>
&#34; wikipedia_page_url&#34;每个主题的值决定了从维基百科中提取的页面,如下面的代码所示:
如何修改上面的JS脚本来拉动并显示每个主题的内容?我知道我需要替换每个&#34; wikipedia_page_url&#34;的价值。在脚本里面这样:
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page=<?php echo $condition['wikipedia_page_url']; ?>&callback=?",
但我不知道从哪里拿走它。有什么建议吗?
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page=Tourette_syndrome&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
var markup = data.parse.text["*"];
var i = $('<div></div>').html(markup);
// remove links as they will not work
i.find('a').each(function() { $(this).replaceWith($(this).html()); });
// remove any references
i.find('sup').remove();
// remove cite error
i.find('.mw-ext-cite-error').remove();
$('#article').html($(i).find('p'));
},
error: function (errorMessage) {
}
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="article"></div>
&#13;
答案 0 :(得分:1)
您可以将主题保存在javascript数组中,然后循环遍历它们。
$(document).ready(function(){
var topics = ['Dementia', 'Topic2', 'Topic3'];
for(var i = 0; i < topics.length; i++) {
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page="+topics[i]+"&callback=?",
... the rest of your ajax config
}); //end of ajax
} //end of loop
}); //end of .ready();