[英]Display response(xml) by making a HTTP GET request using javascript?
我对JS非常陌生,已经完成了研究,但我想我使用的是错误的技术或某种方法。 像在python中一样,我们执行GET请求:
request_text = requests.get(url).text
我想做同样的事情,但是使用JS,即以raw(xml)格式显示"http://synd.cricbuzz.com/j2me/1.0/livematches.xml"
中的内容,并且我在某个地方找到了该脚本,但是它不起作用。
<h2>AJAX</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "http://synd.cricbuzz.com/j2me/1.0/livematches.xml", false);
xhttp.send();
}
</script>
</body>
</html>
我只需要有关如何执行此操作的指导,即如何使用JS发送GET / POST请求并将其呈现在网页上?
当我使用
function test(url) { var req = new XMLHttpRequest(); req.open('GET', url); req.onload = function() { var section = document.createElement('section'); var h2 = document.createElement('h2'); h2.textContent = 'Received from ' + url; section.appendChild(h2); var pre = document.createElement('pre'); pre.textContent = req.responseText; section.appendChild(pre); document.body.appendChild(section); }; req.onerror = function(evt) { document.body.insertAdjacentHTML('beforeEnd', '<p>Error requesting ' + url + '.<\\/p>'); }; req.send(); } document.addEventListener('DOMContentLoaded', function() { test('http://home.arcor.de/martin.honnen/cdtest/test2011060701.xml'); test('http://synd.cricbuzz.com/j2me/1.0/livematches.xml'); }, false);
当服务器设置为允许对该目录进行CORS请求时,第一个URL起作用,而第二个URL则由于服务器不允许而失败。 因此,除非您使用synd.cricbuzz.com
的脚本提供HTML服务,或者除非您可以更改synd.cricbuzz.com
的配置以允许CORS请求,否则您将无法从该服务器请求XML。
还要注意,在现代浏览器(当前版本的Mozilla,Chrome,Edge)中,可以使用基于Promise
的fetch
方法代替XMLHttpRequest
,如下所示。 但是对于fetch
,相同的原始策略并没有什么不同,因此与上述相同。
function test(url) { fetch(url).then(function(response) { if(response.ok) { response.text().then(function(text) { var section = document.createElement('section'); var h2 = document.createElement('h2'); h2.textContent = 'Received from ' + url; section.appendChild(h2); var pre = document.createElement('pre'); pre.textContent = text; section.appendChild(pre); document.body.appendChild(section); }); } else { document.body.insertAdjacentHTML('beforeEnd', '<p>Error requesting ' + url + '; status: ' + response.status + '.<\\/p>'); } }) .catch(function(error) { document.body.insertAdjacentHTML('beforeEnd', '<p>Error "' + error.message + '" requesting ' + url + '.<\\/p>'); }); } document.addEventListener('DOMContentLoaded', function() { test('http://home.arcor.de/martin.honnen/cdtest/test2011060701.xml'); test('http://synd.cricbuzz.com/j2me/1.0/livematches.xml'); }, false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.