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