在jquery中将2个变量从1个函数传递给另一个函数

时间:2011-09-22 04:42:30

标签: php javascript jquery ajax json

好的,我从JSON获得PHP表单的结果来进行登录验证。我想查看他们的帐户是否已激活,我做得很好。如果不是我显示jQuery错误但我希望能够让他们重新发送激活电子邮件。我可以将用户名密码传递给显示JSON错误的函数,但是如何将该数据传递给新函数来处理新电子邮件?以下是我到目前为止的情况:

// LOGIN Validation

$(function(){
  $("#jq_login").submit(function(e){
     e.preventDefault();  

     $.post("widgets/login_process.php", $("#jq_login").serialize(),
       function(data){    
        if(data.all_check == 'invalid'){
          $('div.message_error').hide();
          $('div.message_success').hide();
          $('div.message_error').fadeIn();
          $('div.message_error').html(
            "<div>UserId and/or password incorrect. Try again.</div>"
          );

        } elseif(data.user_check == 'invalid'){
          $('div.message_error').hide();
          $('div.message_success').hide();
          $('div.message_error').fadeIn();
          $('div.message_error').html(
            "<div>UserId and/or password incorrect. Try again.</div>"
          );

        } elseif (data.activated_check == 'invalid'){
          $('div.message_error').hide();
          $('div.message_success').hide();
          $('div.message_error').fadeIn();
          $('div.message_error').html(
            "<div>Your account has not been activated. Please check your "  + 
            "email and follow the link to activate your account. Or click " +
            "<a href='#' id='resend'>here</a> to re-send the link.</div>"
          );

        } else {
          $('div.message_error').hide();
          $('div.message_success').fadeIn();
          $('div.message_success').html(
            "<div'>You are now logged in. Thank you </div>"
          );

          window.location.replace("producer.php");
          return false;
        }
      }, "json");
    });
  });             

  $(function(){
    $("#resend").live('click', function(event){
      event.preventDefault();
      alert(data.username);

      var data = 'username=' + data.username + 'password=' + data.password;

      $.ajax
    });                  
  });

我是新手,所以我不了解来回传递数据的所有细节。

谢谢。

克雷格

2 个答案:

答案 0 :(得分:0)

服务器是否可以只使用返回的json附加确认链接?

      $('div.message_error').html(
        "<div>Your account has not been activated. Please check your "  + 
        "email and follow the link to activate your account. Or click " +
        "<a href='" + data.activation_url + "' id='resend'>here</a> to re-send the link.</div>"
      );

答案 1 :(得分:0)

使用Ajax并不是真的“来回传递数据”,而只是传递回调。当你将function() { ... }作为函数参数放置时,这就是你正在做的事情 - 你正在创建一个回调。

我认为最好的做法是将其重构为几个独立的功能。一个好的最佳实践是使每个函数只做一件事,而不是在函数内的函数内定义函数。

重构后,我们可以更清楚地“重用”重新发送 - 激活链接的用户名和密码。

(function() { // to keep these functions out of the global scope(†)
  // this will be called when the login form is submitted
  function handleLogin(evt) {
    evt.preventDefault();

    // same as your code except that instead of creating a function here
    // we instead pass `handleLoginResponse`, which is a function we'll
    // define later
    $.post( 'widgets/login_process.php',
      $(this).serialize(), // <-- In events, `this` refers to the element that 
      handleLoginResponse, //     fired the event--in this case the form, so we
      'json'               //     don't need its id, we can just give `this`
    );                     //     to jQuery.
  }

  // This is the function we gave to $.post() above, and it'll be called when
  // the response is received.
  function handleLoginResponse(data) {
    // Here we decide what message to show based on the response, just like
    // in your code, but we call a function (showError or showSuccess) to
    // avoid repeating ourselves.
    if(data.all_check == 'invalid') {
      showError("UserId and/or password incorrect. Try again.");

    } else if(data.user_check == 'invalid') {
      showError("UserId and/or password incorrect. Try again.");

    } else if(data.activated_check == 'invalid') {
      showError("Your account has not been activated. Please check your " + 
                "email and follow the link to activate your account. Or " +
                "click <a href='#' id='resend'>here</a> to re-send the link."
      );

    } else {
      showSuccess("You are now logged in. Thank you.");
      redirectToLoggedInPage();
    }
  }

  // the function that shows error messages
  function showError(message) {
    $('.message_success').hide();
    $('.message_error').hide().            // jQuery chaining keeps things tidy
      html('<div>' + message + '</div>').
      fadeIn();
  }

  // the function that shows success messages
  function showSuccess(message) {
    $('div.message_error').hide();
    $('div.message_success').fadeIn().
      .html('<div>' + message '</div>');
  }

  // this method is called when the "resend" link is clicked
  function handleResendClicked(evt) {
    evt.preventDefault();

    // send another Ajax request to the script that handles resending, using
    // the form values as parameters
    $.get( './resend_activation.php',
      $('#jq_login').serialize(),
      handleResendResponse // again we've defined this function elsewhere
    );
  }

  // called when the Ajax request above gets a response
  function handleResendResponse(data) {
    // of course you can do whatever you want with `data` here
    alert('resend request responded with: ' + data);
  }

  // called from handleLoginResponse when the login is successful
  function redirectToLoggedInPage() {
    window.location = './producer.php';
  }

  // finally, our document.ready call
  $(function() {
    // pass the names of the functions defined above to the jQuery
    // event handlers
    $("#jq_login").submit(handleLogin);
    $("#resend").live('click', handleResendClicked);
  });
}());

当然,你不会总是像这样编码 - 有时真的 最好只是在现场定义一个匿名的function() { ... } - 但是当事情变得嵌套时 - 这是一个解开事物的好方法,并且趋向于使前进的道路更加清晰。

(†)Anonymous closures for limiting scope