2017-05-17 3 views
0

URLにajax呼び出しを行い、結果としてpタグのみを使用しようとしています。これをどのように実装できますか?例えばAjaxのWebサイトURLへの呼び出し、結果を解析して段落タグを取得する方法

私が持っている場合:

$.get("www.foobar.com",function(result){ 
console.log(result) 
}); 

//this will return all the html contents of foobar.com as a string so I might get <html><head></head><body> <h1>foobar</h1><h3>Some Text</h3><p>Hello World</p><br><p> this is a cool site</p>

しかし、私は唯一のPタグの内容(Hello Worldのを、これはクールなサイトです)したい私はこれをどのように行うことができますか?

答えて

0

これは、簡単なJavaScriptで行うことができます。

var str; //Placeholder for string returned from AJAX 
var result = ""; //This is where the result will be stored. 
var strlength = str.length; //Store end of string 

var start = str.indexOf("<p>"); //Position of first <p>; 
while(start != -1) //Index will be -1 if no <p> is found 
{ 
    var end = str.indexOf("</p>"); //Position of first </p> 
    result += str.slice(start+3, end); //Add section between start and end to result (+3 is to remove <p> from string) 
    str = str.slice(end+4, strlength); //New string to check with first section and everythign before it removed (+4 is to move past </p>) 
    start = str.indexOf("<p>"); //Get next position 
} 

注私は「P」の要素の「中身」に文字通りあなたを取りました。あなたは「P」タグを維持したい場合は、その後に変更します。

result += str.slice(start, end+4); 

あなたには、いくつかの方法で結果をスタイルにしたい場合は、間に結果に物事を追加することができます。例:

result += "<br>"; 
関連する問題