我想要使用JSONP獲取源代碼形式的URL網頁。 這是代碼:使用JSONP從JavaScript網頁獲取源代碼使用JSONP
<script type="text/javascript">
var your_url = '';
$(document).ready(function(){
jQuery.ajax = (function(_ajax){
var protocol = location.protocol,
hostname = location.hostname,
exRegex = RegExp(protocol + '//' + hostname),
YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
query = 'select * from html where url="{URL}" and xpath="*"';
function isExternal(url) {
return !exRegex.test(url) && /:\/\//.test(url);
}
return function(o) {
var url = o.url;
if (/get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url)) {
// Manipulate options so that JSONP-x request is made to YQL
o.url = YQL;
o.dataType = 'json';
o.data = {
q: query.replace(
'{URL}',
url + (o.data ?
(/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
: '')
),
format: 'xml'
};
// Since it's a JSONP request
// complete === success
if (!o.success && o.complete) {
o.success = o.complete;
delete o.complete;
}
o.success = (function(_success){
return function(data) {
if (_success) {
// Fake XHR callback.
_success.call(this, {
responseText: data.results[0]
// YQL screws with <script>s
// Get rid of them
.replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
}, 'success');
}
};
})(o.success);
}
return _ajax.apply(this, arguments);
};
})(jQuery.ajax);
$.ajax({
url: your_url,
type: 'GET',
success: function(res) {
var text = res.responseText;
//document.getElementById("contenuto").innerHTML = text;
alert(text);
}
});
});
</script>
我印有一個警報的所有源代碼,從所述URL。
alert(text);
首先,如何知道打印的代碼是否是頁面的所有網頁代碼? 如果我嘗試這樣做
document.getElementById("contenuto").innerHTML = text;
這就是結果:
\ \ <'+'/ins>\ \ \ '); } ]]>
我試圖用HTML DOM打印一個元素,這樣
document.getElementById("contenuto").innerHTML = text;
var elem = text.getElementById("strip_adv").innerHTML;
document.getElementById("contenuto_1").innerHTML = elem;
}
做
但是,這是JS控制檯上的錯誤:
text.getElementById is not a function
概述: 我想使用JSONP從URL獲取網頁的源代碼。 我會從返回的文本中使用HTML DOM,只保留我需要的元素/類。我是JS的新手,我想了解更多關於JS的&。
'responsetext'不是元素。你應該嘗試解析它。 – mok
@mok如果我試圖使用此代碼打印 document.getElementById(「contenuto」)。innerHTML = text; 這是結果是:[screen1](https://postimg.org/image/erjvgz9s7/) 爲什麼?首先,我打印整個「字符串」(頁面的源代碼),檢查它是否完整。但我不能。 – Jackie
似乎你的代碼沒有正確解析頁面。試試這樣一個簡單的頁面[http://www.murgaboots.com/aboutus.html](隨機選擇一個簡單的網頁)。無論如何,答案就是我之前說過的,你應該解析'responsetext'。 – mok