简体   繁体   中英

Can I return true to asp.net OnClientClick After an Ajax call? Or maybe some other way?

I m using Ajax call to check whether a user has logged in or not. If not, show login dialog; else I want OnClientClick to return true so that the form will submit. I m thinking about using a global variable and check it until Ajax gives it a value... I am not sure whether it is the right way? Thanks!

(the server side code already works)

in .ascx:

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

in .js:

function buttonSubmitOnclick() {
  showLogin();
  //What to do here??? how to get the result after the ajax call?  
}


//========== 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
        };//else is it possible to return a true to buttonSubmitOnclick?
    }
  }
  xmlhttp.open("GET", "AjaxService.aspx?t=auth", true);  
  xmlhttp.send();
}

when the condition satisfy, you can submit the form manually on response of ajax call using document.forms['myForm'].submit() . Make the button as normal button(not submit button) and remove the return before the function call in the button element and then do as below:

function buttonSubmitOnclick() {
  showLogin();
  }


//========== 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(); // display the pop up
        }else{
        document.forms['myForm'].submit() // else submit the form,'myForm' is form id'
            }
    }
  }
  xmlhttp.open("GET", "AjaxService.aspx?t=auth", true);  
  xmlhttp.send();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM