2017-02-25 61 views
0

我的任务是使用维基百科API从新泽西网站检索图像,并提出了两种执行类似任务的方法。第一种方法是使用JSON,但它拉动了整个页面。使用jQuery和/或AJAX从网站中提取当前图像?

<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> 

而且我还使用了一个AJAX请求与jQuery配对,但它只拉文本。

<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) { 
    } 
});  

});  

哪种方法是最好的解决这个问题,我怎么能解决这个问题拉只有当前的图像,以及属性的用户名,以每张图片?

谢谢!

+0

检查我的答案。 – Mouneer

+0

所以我做到了,但图片没有加载在我的页面上。虽然这些照片确实在那里。当我运行我的调试器并检查了控制台时,它引发了错误SCRIPT7002:XMLHTTPError:0x2。任何快速解决方法? – Kevin

+0

确保您正在处理的图像不是相对路径。当然,只有绝对/完整路径才有效。 – Mouneer

回答

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]); 
}});