【问题标题】:How to set request header in jquery如何在jquery中设置请求头
【发布时间】:2019-10-13 17:59:07
【问题描述】:

我在网页上执行 GET 请求,但它不起作用,因为“请求的资源上不存在‘Access-Control-Allow-Origin 标头”,我认为这意味着我需要标头。我将如何在我的 jquery 中的网站上设置此标头。 我的代码如下:

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      <title>Sample Page</title>
      <script>
     var settings = {
       "async": true,
       "crossDomain": true,
       "url": "https://games.roblox.com/v1/games?universeIds=140239261",
       "method": "GET"
     }
         $.ajax(settings).done(function (response) {
           console.log(response);
           var content = response.data.playing;
           $("#counter").append(content);
         });
      </script>
   </head>
   <body>
      <h1>Sample Page</h1>
      <div id="counter">playing: </div>
   </body>
</html>

提前感谢您的帮助。我找不到使用 jquery 的方法(至少我的代码是如何设置的),所以请帮忙! (我是 javascript 的初学者,所以尽量让答案简单。)

【问题讨论】:

    标签: javascript jquery html json get


    【解决方案1】:

    当您收到此错误时,这实际上意味着您正在尝试向与您的页面所在的域不同的域发送请求,根据您的服务器端技术,您应该在您的服务器上启用CORS 以接受来自其他脚本的请求您的服务器尚未生成。

    【讨论】:

      【解决方案2】:

      你可以这样做

      $.ajax({
          url: 'https://games.roblox.com/v1/games?universeIds=140239261', 
          dataType: 'jsonp', // This alone should also work without the beforeSend below
          beforeSend: function(xhr){
                         xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
                      }
      })
      

      但是,即使这样也只有在服务器跨源请求时才有效

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-28
        • 2013-04-24
        • 2012-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多