2016-09-20 34 views
-3

我使用下面的C#代碼,以獲得HttpWebResponseJavascript代碼,以獲得HttpWebResponse

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); 
httpWebRequest.Method = "POST"; 
httpWebRequest.ContentLength = 0; 
httpWebRequest.AllowAutoRedirect = false; 
return (HttpWebResponse)httpWebRequest.GetResponse(); 

我想在JavaScript類似的代碼來獲取HTTP網頁響應。像

var xhr=new XMLHttpRequest(); 
xhr.open('POST',url,true); 
xhr.send(); 

我曾嘗試代碼我不能夠獲得響應(即狀態代碼-301和重定向URL)。

在此先感謝!

+0

這不是C#代碼? –

+0

「我要......代碼」不屬於SO詞彙表。請顯示,你迄今爲止所做的解決你的問題。 – Teemu

+0

是Levi Steenbergen。 – user1992728

回答

1

如果我理解正確的,你需要的是這樣的:

var xhttp = new XMLHttpRequest(); 
xhttp.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
    console.log(this.responseText); 
    } 
}; 
xhttp.open("POST", "http://localhost/myUrl", true); 
xhttp.send(); 
0

使用純JavaScript:

<script type="text/javascript"> 
function loadXMLDoc() { 
    var xmlhttp = new XMLHttpRequest(); 

    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == XMLHttpRequest.DONE) { 
      if (xmlhttp.status == 200) { 
       document.getElementById("myDiv").innerHTML = xmlhttp.responseText; 
      } 
      else if (xmlhttp.status == 400) { 
       alert('There was an error 400'); 
      } 
      else { 
       alert('something else other than 200 was returned'); 
      } 
     } 
    }; 

    xmlhttp.open("GET", "ajax_info.txt", true); 
    xmlhttp.send(); 
} 
</script> 

使用jQuery:

$.ajax({ 
    url: "test.html", 
    context: document.body, 
    success: function(){ 
     $(this).addClass("done"); 
    } 
}); 
+0

你好,謝謝你的回覆..在嘗試這個之後,我沒有收到任何迴應,我應該得到的是狀態碼301和重定向網址。 – user1992728

+0

@ user1992728:正如https://en.wikipedia.org/wiki/HTTP_301中所述:__ HTTP永久移動的響應狀態代碼301用於永久性URL重定向,意味着當前鏈接或使用接收到響應的URL的記錄應該更新。應在響應中包含的位置字段中提供新的URL。 301重定向被認爲是將用戶從HTTP升級到HTTPS的最佳實踐.__ –

+0

是的,當我使用c#代碼時,我在位置字段中獲得了重定向url,但是使用javascript我無法獲得任何響應,是否有人可以幫助一樣。 – user1992728