0

我需要从使用 GET 从服务器的用户列表中发布用户名,但如何将该用户名作为字符串发布。任何帮助表示赞赏,在此先感谢!

  //get a list of users from server side
$.getJSON(
  '/userlist',
  function(data) {
    var user = data.users;
    $("#utbildning").text(user[1].username);
    $("#tekniker").text(user[2].username);
  }
);

//post user name and password at login  
$(document).ready(function() {
  $("#knapp").click(function(){

    //name of the user should be a name from the user list comes from server
    var name=$.getJSON(
      '/userlist',
      function(data) {
        var user = data.users;
        user[1].username;
      }
    );
    var pass=$("#kod").val(); //password from input field
    var data = new Object();
    data["username"] = name;
    data["password"] = pass;

    $.ajax(
      {
         url: "/login",
         data: JSON.stringify(data),
         processData: false,
         type: 'POST',
         contentType: 'application/json',
      }
    );
  });
})
4

1 回答 1

1

多个错误:

  • 除非发生重大变化,否则您将无法使用任何东西var name = $.getJson(...
  • 然后由于 $.getJSON 是异步的,你应该做任何使用 $.getJSON 回调方法中的 ajax 调用中设置的变量。就像您在第一次通话中所做的那样。

这是一个“更正”的版本(如果您的代码是正确的):

  //get a list of users from server side
$.getJSON(
  '/userlist',
  function(data) {
    var user = data.users;
    $("#utbildning").text(user[1].username);
    $("#tekniker").text(user[2].username);
  }
);

//post user name and password at login  
$(document).ready(function() {
  $("#knapp").click(function(){

    //name of the user should be a name from the user list comes from server
    $.getJSON(
      '/userlist',
      function(data) {
        var user = data.users;
        var name = user[1].username;
        var pass=$("#kod").val(); //password from input field
        var data = new Object();
        data["username"] = name;
        data["password"] = pass;

        $.ajax(
          {
             url: "/login",
             data: JSON.stringify(data),
             processData: false,
             type: 'POST',
             contentType: 'application/json',
          }
        );
      }
    );
  });
})
于 2012-04-26T14:34:42.397 回答