2016-02-25 29 views
1

我試圖在JavaScript中做Cors請求。這是我的代碼:刪除模板中的Django的URL前綴

 function createCORSRequest(method, url) { 
     var xhr = new XMLHttpRequest(); 
     if ("withCredentials" in xhr) { 

     // Check if the XMLHttpRequest object has a "withCredentials" property. 
     // "withCredentials" only exists on XMLHTTPRequest2 objects. 
     xhr.open(method, url, true); 

     } else if (typeof XDomainRequest != "undefined") { 

     // Otherwise, check if XDomainRequest. 
     // XDomainRequest only exists in IE, and is IE's way of making CORS requests. 
     xhr = new XDomainRequest(); 
     xhr.open(method, url); 

     } else { 

     // Otherwise, CORS is not supported by the browser. 
     xhr = null; 

     } 
     return xhr; 
    } 

function makeCorsRequest() { 
    // All HTML5 Rocks properties support CORS. 
    var url = 'otherdomain.ashx?username=xxx&password=xxx&sportsBook=xxx&sportsType=xxx&gameType=xxx'; 

    var xhr = createCORSRequest('GET', url); 
    if (!xhr) { 
    alert('CORS not supported'); 
    return; 
    } 

    // Response handlers. 
    xhr.onload = function() { 
    var text = xhr.responseText; 
    var title = getTitle(text); 
    alert('Response from CORS request to ' + url + ': ' + title); 
    }; 

    xhr.onerror = function() { 
    alert('Woops, there was an error making the request.'); 
    }; 

    xhr.send(); 
} 

但我無法得到請求。當我看到控制檯時,http://127.0.0.1:8000/admin/managebadge/otherdomain.ashx?username=xxx&password=xxx&sportsBook=xxx&sportsType=xxx&gameType=xxx 404(未找到)。我如何刪除模板中的「http://127.0.0.1:8000/admin/managebadge」(url前綴)?我使用Django。謝謝。

+0

我可以問你爲什麼要使用一個GET請求在所有的密碼嗎?除此之外,它不清楚你想解決什麼問題 – Sayse

+0

@Sayse url是一個API。支持GET和POST方法。當我執行makeCorsRequest()時,沒有顯示警報。然後我檢查元素控制檯選項卡,出現錯誤,我請求的網址仍包含前綴「http://127.0.0.1:8000/admin/managebadge」。我想刪除該前綴。謝謝。 – Krisnadi

+0

你是在js中指定完整的URL:'var url ='http://otherdomain.ashx?username = xxx&password = xxx&sportsBook = xxx&sportsType = xxx&gameType = xxx';'? – doru

回答

0

瀏覽器正在將您的網址視爲相對網址。嘗試:

var url = '://otherdomain.ashx?username=xxx&password=xxx&sportsBook=xxx&sportsType=xxx&gameType=xxx'; 

,或者

var url = 'http://otherdomain.ashx?username=xxx&password=xxx&sportsBook=xxx&sportsType=xxx&gameType=xxx'; 

瞭解更多關於瀏覽器如何解析此網址: http://www.webreference.com/html/tutorial2/3.html

+0

它的工作原理。但這是另一個問題。 XMLHttpRequest無法加載http:// otherdomain .....沒有Access-Control-Allow-Origin標頭存在於請求的源代碼中。順便說一句謝謝。 – Krisnadi