jQuery - 简单的全局变量

时间:2014-03-01 01:50:06

标签: jquery variables global

我自己在学习jQuery,请在这里需要一些帮助。

我不知道为什么,但是这段代码中的“msg”变量到底是空的。

jQuery(function($) {
  $('#mailing').submit(function(e) {
    e.preventDefault();

    var msg = '';

    $.ajax({
      type: "POST",
      url: "ajx_mailing.asp",
      data: 'email=test@test.com',
      cache: false,
      dataType: "text",
      complete: function(data){
        if (data.responseText = 'ok') {
          msg = 'The e-mail was included with success!';
        } else {
          msg = 'There is a problem, please check the e-mail!';
        }
      },
      error: function(data) {
        msg = 'Error! Please, try again latter!';
      },
    });

    /* http://www.ericmmartin.com/projects/simplemodal/ */

    $('#simplemodal').modal({
      minWidth: 410,
      minHeight: 120,
      position: ['30%',],
      overlayId: 'msgbox-overlay',
      containerId: 'msgbox-container',
      onShow: function(dialog) {
        var modal = this;
        $('.header', dialog.data[0]).append('Mailing List');
        $('.message', dialog.data[0]).append(msg);
        $('.ok', dialog.data[0]).click(function() {
          modal.close();
        });
      }
    });

  });
});

模态消息是空白的?你知道为什么吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

$.ajax 是一个可以随时完成的异步函数。因此,变量msg的值将在一段时间后发生变化,之后将执行()$('#simplemodal').modal({代码,这就是缺少值的原因。所以只需在ajax成功或错误之后初始化()$('#simplemodal').modal({

jQuery(function($) {
    $('#mailing').submit(function(e) {
        e.preventDefault();
        var msg = '';
        $.ajax({
            type: "POST",
            url: "ajx_mailing.asp",
            data: 'email=test@test.com',
            cache: false,
            dataType: "text",
            complete: function(data) {
                if (data.responseText = 'ok') {
                    msg = 'The e-mail was included with success!';
                } else {
                    msg = 'There is a problem, please check the e-mail!';
                }
                modal();
            },
            error: function(data) {
                msg = 'Error! Please, try again latter!';
                modal();
            },
        });
        /* http://www.ericmmartin.com/projects/simplemodal/ */

        function modal() {
            $('#simplemodal').modal({
                minWidth: 410,
                minHeight: 120,
                position: ['30%', ],
                overlayId: 'msgbox-overlay',
                containerId: 'msgbox-container',
                onShow: function(dialog) {
                    var modal = this;
                    $('.header', dialog.data[0]).append('Mailing List');
                    $('.message', dialog.data[0]).append(msg);
                    $('.ok', dialog.data[0]).click(function() {
                        modal.close();
                    });
                }
            });
        }
    });
});