<p>可以使用以下方式在<script>标签中添加请求头:</p>
<ol>
<li>使用XMLHttpRequest对象发送请求,然后将响应的数据插入到页面中。</li>
</ol>
<pre><code class="language-javascript">var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/data.json', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 &amp;&amp; xhr.status == 200) {
    var data = JSON.parse(xhr.responseText);
    // 将数据插入到页面中
  }
};
xhr.send();
</code></pre>
<ol start="2">
<li>使用jQuery库的$.ajax()方法发送请求,然后将响应的数据插入到页面中。</li>
</ol>
<pre><code class="language-javascript">$.ajax({
  url: 'http://example.com/data.json',
  headers: {
    'Content-Type': 'application/json'
  },
  success: function(data) {
    // 将数据插入到页面中
  }
});
</code></pre>
<ol start="3">
<li>在HTML文档中直接嵌入JavaScript代码,使用XMLHttpRequest对象发送请求,然后将响应的数据插入到页面中。</li>
</ol>
<pre><code class="language-html">&lt;script&gt;
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'http://example.com/data.json', true);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 &amp;&amp; xhr.status == 200) {
      var data = JSON.parse(xhr.responseText);
      // 将数据插入到页面中
    }
  };
  xhr.send();
&lt;/script&gt;
``
</code></pre>
script标签怎么添加请求头

原文地址: http://www.cveoy.top/t/topic/cqWm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录