我正在尝试完成简单但看似复杂的任务。我正在尝试从纯 JavaScript(前端)到 aspx 页面(后端)进行 AJAX 调用,而不包含任何 asp ajax 库,旨在前端不呈现任何 asp 页面,即前端仅使用 html+JS。
事情是这样的,在前端,这段 js 代码将使用变量向 asp 页面发送异步调用。该变量源自文本框值。
function handleRequest() {
if (xhr.readyState < 4) {
return; // The response is not available yet , we do nothing
}
if (xhr.status !== 200) {
alert('Error!'); // error HTTP
return;
}
}
function getValue() {
var textVal = document.getElementById("test1").value;
xhr.open('GET', 'WebForm1.aspx?q=' + textVal , true);
xhr.send();
var response = xhr.responseText;
document.getElementById("bdy").innerHTML = response;
}
var btn = document.querySelector("button");
var xhr = new XMLHttpRequest();
var body = document.getElementById("bdy");
xhr.onreadystatechange = handleRequest;
document.getElementById("header").innerHTML = Date();
btn.addEventListener('click', getValue, true);
现在,在后端 asp 代码上,它将使用服务器的时间戳来回显文本框值。
protected void Page_Load(object sender, EventArgs e)
{
string getRequest = Request.QueryString["q"];
DateTime dt = DateTime.Now;
string responseText = getRequest + dt.ToString();
Response.Write(responseText);
}
最后,当我进行同步调用时,这段代码工作完美,即 xhr.open('GET', 'WebForm1.aspx?q=' + temp, false);但如果我发送异步调用,即 xhr.open('GET', 'WebForm1.aspx?q=' + temp, true); 则会失败;
我非常感谢您的帮助。
最佳答案
使用异步操作获取的数据的代码应放置在数据到达后调用的回调中。您已经有这样的回调函数 - handleRequest
:
function handleRequest() {
if (xhr.readyState < 4) {
return; // The response is not available yet , we do nothing
}
if (xhr.status !== 200) {
alert('Error!'); // error HTTP
return;
}
var response = xhr.responseText;
document.getElementById("bdy").innerHTML = response;
}
function getValue() {
var textVal = document.getElementById("test1").value;
xhr.open('GET', 'WebForm1.aspx?q=' + textVal , true);
xhr.send();
}
关于Javascript Ajax 前端调用 asp.net C# 后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33208718/