使用jQuery和/或AJAX从网站中提取当前图像?

时间:2017-02-25 14:21:13

标签: javascript jquery ajax

我的任务是使用维基百科API从新泽西网站上检索图像,我想出了两种方法来完成类似的任务。第一种方法是使用JSON,但它拉动了整个页面。

<script type="text/javascript">
$.getJSON('http://en.wikipedia.org/w/api.php?action=parse&page=New_Jersey&prop=text&format=json&callback=?', function(json) { 
$('#wikiInfo').html(json.parse.text['*']); 
$("#wikiInfo").find("a:not(.references a)").attr("href", function(){ return "http://www.wikipedia.org" + $(this).attr("href");}); 
$("#wikiInfo").find("a").attr("target", "_blank"); 
});
</script>

<div id="wikiInfo">&nbsp;</div>

我还使用了与jQuery配对的AJAX请求,但它只提取了文本。

<script type="text/javascript">
    $(document).ready(function(){
$.ajax({
    type: "GET",
    url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&page=New_Jersey&callback=?",
    contentType: "application/json",
    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) {
    }
});    

});    

哪种方式最适合解决此问题,如何修复它以仅提取当前图像,以及将用户名归因于每张图片?

谢谢!

1 个答案:

答案 0 :(得分:0)

获取图片的一种可能方法是使用Regular Expressions

ES6版本:

$.getJSON('http://en.wikipedia.org/w/api.php?action=parse&page=New_Jersey&prop=text&format=json&callback=?', function(json) { 
const text = json.parse.text['*'];
const regex = /([-\w+\.\/]+(?:png|svg))/gmi;
let m;
while ((m = regex.exec(text)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    console.log(`Found match: ${m[1]}`);
}});

ES5版本:

$.getJSON('http://en.wikipedia.org/w/api.php?action=parse&page=New_Jersey&prop=text&format=json&callback=?', function(json) { 
var text = json.parse.text['*'];
var regex = /([-\w+\.\/]+(?:png|svg))/gmi;
var m;
while ((m = regex.exec(text)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    console.log('Found match: ' + m[1]);
}});