簡體   English   中英

如何在 jquery 中設置請求 header

[英]How to set request header in jquery

我在網頁上執行 GET 請求,但它不起作用,因為“請求的資源上沒有 'Access-Control-Allow-Origin header”,我認為這意味着我需要 header。 我如何在我的 jquery 的網站上設置這個 header。 我的代碼如下:

 <: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 的初學者,所以盡量讓答案簡單。)

當您收到此錯誤時,這實際上意味着您正在嘗試將請求發送到與您的頁面所在的域不同的域,根據您的服務器端技術,您應該在您的服務器上啟用CORS以接受來自您的服務器沒有的其他腳本的請求生成。

你可以做這樣的事情

$.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', '*');
                }
})

但是,即使這樣也只有在服務器跨源請求時才有效

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM