2015-10-19 91 views
1

我想完成简单但看起来很复杂的任务。我正在尝试从纯JavaScript(前端)到aspx页面(后端)进行AJAX调用,而不包括任何针对前端没有asp页面呈现的asp ajax库,即仅用于前端的html + JS。Javascript Ajax前端调用asp.net C#后端

所以这里是怎么回事,在前端这个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 =?' +温度,FALSE);但如果我发送异步调用,例如xhr.open('GET','WebForm1.aspx?q ='+ temp,true),则失败。

我真的很感谢你的帮助。

+0

*但失败,如果我发送异步调用* - 什么是错误?您应该能够通过浏览器中的Web控制台来了解这一点。 – niksofteng

+0

页面加载时或当我单击按钮时,Web控制台是空白的(不显示任何错误)。 –

+0

附注:请考虑更常规的方法 - jQuery + ASP.Net MVC ...手动重写jQuery.ajax调用是痛苦的,迫使WebForms产生明智的响应也很困难。即使使用现有的库,我也不担心缺少问题。由于您当前的项目显然是娱乐/学习练习,因此很难提供具体的帮助 - 我假设您正在寻找调试建议... –

回答

0

我找到了答案。问题在于,在执行AJAX同步调用时,浏览器会在将结果存储到变量响应之前等待服务器的响应,然后显示结果。但是,在进行异步调用时,浏览器不会等待响应,因此响应变量将为空,并且innerHTML将显示nathing。

通过给响应接收代码行添加一个延迟,代码完美工作。这是代码。

setTimeout(function() { 
    var response = xhr.response; 
    document.getElementById("bdy").innerHTML = response; 
}, 50); 

由于

+0

这是一个错误的方式来做到这一点 - 当获得响应需要超过50毫秒时会中断。看到我的答案。 – Igor

1

代码,其使用由异步操作获得的数据应放置在数据到达之后调用的回调。你已经有这样的回调函数 - 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(); 
}