更新. .需要一个Ajax示例,说明客户端如何在不回发的情况下从服务器端获取值

Updated ... need an Ajax example about how client side gets a value from the server side w/o postback

本文关键字:情况下 获取 服务器端 客户端 一个 说明 示例 Ajax 更新      更新时间:2023-09-26

基本上我想检查用户是否使用javascript登录当一个按钮被点击

我知道ajax可以做到这一点,但我不知道从哪里开始…我不想学习整个ajax

有任何简单的代码样本,我可以"借用"?

============================== 更新2 ===================================

我贴出了另一个问题,得到了下面的答案…如果有人有和我一样的问题…

我可以返回true到asp.net OnClientClick Ajax调用后?或者其他方式?

============================== 更新 =====================================

我读了一些例子,但我就是找不到我需要的那个。我可以从服务器端得到结果,然后……卡住了……这是我的代码,请帮助评论中的问题。非常感谢!!

在.ascx:

<asp:Button ID="buttonSubmit" Text="Submit" OnClientClick="return buttonSubmitOnclick()" OnClick="buttonSubmit_Click" runat="server"/>
在js

:

function buttonSubmitOnclick() {
  showLogin();
  //What to do here??? how to return true if the ajax call return 'true'?  
  return true;  //???
}

//========== Ajax ==============
function showLogin() {
  var xmlhttp;
  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
  }
  else {// code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        if (xmlhttp.responseText == "false") {
            $find('modalPopupLogin').show();  //Show Login Dialog
        };
    }
  }
  xmlhttp.open("GET", "AjaxService.aspx?t=auth", true);   //??? should the last parameter be "false"???
  xmlhttp.send();
}

这很直接。由于您正在使用asp.net,可能最简单的方法是使用page方法。asp.net中的页面方法允许你在后台编写。net代码,然后使用javascript方法调用它。page方法必须声明为静态/共享,因为它将在页面生命周期之外被访问。

下面是一些例子:
——http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx
——http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

无论是否使用jQuery,

Page方法都很容易调用。

关于在w3上使用不使用jQuery的Ajax有一些很好的信息,其中最后有一个使用asp的Ajax的工作示例。不需要太多的阅读

问题更新:底部解释了使用异步true和false的区别。

使用async=true, JS不会等待响应,所以你不想在这里处理它:

function buttonSubmitOnclick() {
  showLogin();
  //What to do here??? how to return true if the ajax call return 'true'?  
  return true;  //???
}

一旦xmlhttp.send()运行,js继续前进,从showLogin()返回,并将从buttomSubmitOnclick返回,无论登录响应是否已经返回。

假设async为真,您需要扩展onreadystatechange函数中的条件,以便在responseText == "true"时处理。

xmlhttp.onreadystatechange = function () {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    if (xmlhttp.responseText == "false") {
      $find('modalPopupLogin').show();  //Show Login Dialog
    }else if (xmlhttp.responseText == "true") {
      //Continue the previous/submit action here because we are already authenticated
    }
  }
}