无法更新javaScript全局变量

时间:2015-11-24 22:33:17

标签: javascript jquery html asynchronous

这里我有全局变量userId,我想在signInUserFunction()内更新它,以便在其他函数中使用。我尝试使用varwindow来定义它,但所有这些都无济于事。此变量不会更新。正如我所看到的关于AJAX异步。那么,我该怎么办呢?

是的,我知道用JS进行身份验证并不好,我对它很新。所以,我只是创建随机方法来改进。

var userId = 1;

function signInUser() {
  $.getJSON('http://localhost:8887/JAXRSService/webresources/generic/getAllUsers', function(data) {
  var items = [];
  var i = 0;
  $.each(data, function(firstname, value) {

    var str = JSON.stringify(value);
    data = JSON.parse(str);
    var innerId;
    for (p in data) {
      innerId = data[p].id;
      if ($('#nameSignIn').val() == data[p].first_name && $('#passwordSignIn').val() == data[p].password) { //
        userId = innerId;
        window.location.href = "content.html";
        break;
      } else {
        i++;
        if (i == data.length) {
          alert("Ощибка в логине или пароле!")
        }
       }
      }

    });
  });
}

4 个答案:

答案 0 :(得分:0)

您如何确定是否已设定?看起来在设置之后,您可以导航到其他页面。当你到达那个页面时,你会有一个全新的窗口。

尝试在导航之前提醒值。

已编辑:以下是您可以将其传递到其他页面的方式(但您不应该在真实应用中执行此操作)

restoreState

然后在另一页中,您可以从document.location:

访问它
        window.userId=innerId;
        alert(window.userId);

        //this isn't a very secure way to do this. I DON'T recommend this
        window.location.href = "content.html?id=" + innerId ;

答案 1 :(得分:0)

使用@mcgraphix提出的想法(并给出相同的警告......这肯定不是在生产环境中传输这样的数据的方式),这是一种方法:

function signInUser() {
  var url = 'http://localhost:8887/JAXRSService/webresources/generic/getAllUsers';
  var userId;

  $.getJSON(url, function(data) {
    $.each(data.Actors, function(index, actor) {
      // Cache the values of the #nameSignIn and #passwordSignIn elements
      var name = $('#nameSignIn').val();
      var password = $('#passwordSignIn').val();

      if (actor.first_name === name && actor.password === password) {
        // We have found the correct actor.
        // Extract its ID and assign it to userId.
        userId = actor.id;
        window.location.href = "content.html?userId=" + userId;
      }
    });

    // This alert should only be reached if none of the actor objects
    // has a name and password that matches your input box values.
    alert("Ощибка в логине или пароле!"); 
  });
}

// On the next page...
// Top answer from http://stackoverflow.com/questions/2090551/parse-query-string-in-javascript
// This approach can handle URLs with more than one query parameter,
// which you may potentially add in the future.
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split('&');

  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');

    if (decodeURIComponent(pair[0]) == variable) {
      return decodeURIComponent(pair[1]);
    }
  }

  console.log('Query variable %s not found', variable);
}

var userId = getQueryVariable('userId');

答案 2 :(得分:0)

阅读完我的评论后,您可能想尝试一下:

var userId = 1; 
function signInUser(){
  $.getJSON('http://localhost:8887/JAXRSService/webresources/generic/getAllUsers', function(data){
    var items = [], actors = data.Actors, l = 0;
    $.each(actors, function(i, o){
      l++;
      if($('#nameSignIn').val() === o.first_name && $('#passwordSignIn').val() === o.password){
        userId = o.id;
        // this will redirect before any other code runs -> location = 'content.html';
        if(l === actors.length){
          alert('End of Loop');
        }
      }
    });
  });
}
signInUser();

我不会将敏感数据存储在JSON中,例如密码。使用数据库。也无需同时获取所有数据。

答案 3 :(得分:0)

感谢您的帮助。使用以下内容完成所有操作:

sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')