通过使用javascript发出httpget请求来显示响应(xml)?

2024-04-29 09:29:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我对JS很陌生,我也做过研究,但我猜我使用了错误的技术或者别的什么。 就像在python中发出GET请求一样:

request_text = requests.get(url).text

我想做同样的事情,但使用JS,即以原始(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>

我只需要关于如何做同样的指示,即如何发送一个GET/POST请求使用JS和呈现在网页上?你知道吗


Tags: textcomhttpgetdemojsbuttonh2
1条回答
网友
1楼 · 发布于 2024-04-29 09:29:45

当我使用

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

第一个URL在服务器设置为允许该目录的CORS请求时工作,而第二个URL在服务器不允许时失败。因此,除非您使用来自synd.cricbuzz.com的脚本提供HTML,或者除非您可以更改synd.cricbuzz.com的配置以允许CORS请求,否则您将无法从该服务器请求XML。你知道吗

另请注意,在现代浏览器(当前版本的Mozilla、Chrome、Edge)中,可以使用基于Promisefetch方法,而不是XMLHttpRequest,如下所示。但对于fetch来说,相同的原产地政策并没有什么不同,因此上述相同的政策也成立。你知道吗

相关问题 更多 >