2016-09-20 33 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