2017-02-25 4 views
0

私はWikipedia APIを使用してNew Jerseyのウェブサイトから画像を取得することを任されました。同様の作業を行う2つの方法がありました。最初の方法はJSONを使うことでしたが、ページ全体を引っ張ってしまいました。jQueryまたはAJAXを使用してWebサイトから現在のイメージを取得しますか?

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

});  

ありがとうございます!

+0

私の答えをチェックしてください。 – Mouneer

+0

私はそれをしましたが、写真は私のページに載っていませんでした。写真は間違いなくそこにあった。デバッガを実行してコンソールをチェックすると、エラーSCRIPT7002:XMLHTTPError:0x2が返されました。それを修正する簡単な方法はありますか? – Kevin

+0

作業中の画像が相対パスでないことを確認してください。確かに、完全/完全パスのみが機能します。 – Mouneer

答えて

0

イメージを取得する方法の1つは、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]); 
}}); 
関連する問題