如何将JavaScript post代码更改为asp.net HttpWebRequest
我有一个JavaScript代码,可以向web Url发送POST请求并获取响应。响应包含一个字符串和一些cookies,现在我想将其转换为VB.net aspx代码,因此,由于跨域问题,我编写了此操作服务器端,但代码不起作用,所有响应都有空正文。我能请求一些帮助吗 JavaScript代码如何将JavaScript post代码更改为asp.net HttpWebRequest,javascript,asp.net,vb.net,httpwebrequest,httpwebresponse,Javascript,Asp.net,Vb.net,Httpwebrequest,Httpwebresponse,我有一个JavaScript代码,可以向web Url发送POST请求并获取响应。响应包含一个字符串和一些cookies,现在我想将其转换为VB.net aspx代码,因此,由于跨域问题,我编写了此操作服务器端,但代码不起作用,所有响应都有空正文。我能请求一些帮助吗 JavaScript代码 function goldprice_req(deltas, goldurl) { (function ($) { $.ajax('Some URL?_t=' + timenow , {
function goldprice_req(deltas, goldurl) {
(function ($) {
$.ajax('Some URL?_t=' + timenow , {
headers: { "Content-type": "application/x-www-form-urlencoded" },
data: { 'id': goldurl },
cache: false,
type: "POST",
dataType: "json",
contentType: "application/json",
success: goldpriceSuccess,
error: function (xhr, status, error) {
console.log(status);
failure++;
setTimeout(function () { goldprice_req(deltas, goldurl); }, 5000);
if (failure >= 3) {
if (!$('#ajaxfailure').html())
$('#content-top').prepend('<p id="ajaxfailure">Error.</p>');
$('#ajaxfailure').show();
}
}
});
})(jQuery);
}
Dim postdt As String = ""
Dim enc As UTF8Encoding
Dim postdatabytes As Byte()
Dim cookie As New CookieContainer()
Dim request1 As HttpWebRequest = HttpWebRequest.Create("Some Url" & timenow )
request1.CookieContainer = cookie
request1.Method = "POST"
enc = New System.Text.UTF8Encoding()
postdatabytes = enc.GetBytes(postdt)
request1.Headers("ContentType") = "application/x-www-form-urlencoded"
request1.ContentLength = postdatabytes.Length
Using stream = request1.GetRequestStream()
stream.Write(postdatabytes, 0, postdatabytes.Length)
End Using
Dim response1 As HttpWebResponse = DirectCast(request1.GetResponse(), HttpWebResponse)
For Each cok As Cookie In response1.Cookies
cookie.Add(cok)
Next
Dim htmlbody As String
Dim resstr As Stream = response1.GetResponseStream
Dim reader As StreamReader = New StreamReader(resstr, True)
While reader.Peek >= 0
htmlbody = reader.ReadToEnd
End While
Response.Write(htmlbody)
response1.Close()
reader.Close()
我的代码出了什么问题?您遇到了什么错误?它没有给出任何错误,但响应为nothing或empty。您的代码中有两个问题:1。您希望返回cookie,但只返回HTML。2.即使您希望从返回的cookie中获得信息,您也不能只通过Response.Write来完成。对不起,我可以请您描述一下代码的问题吗?请检查:我认为您可能需要更改代码体系结构。通过使一个web服务可由AJAX调用,该web方法将返回cookies。