使用jQuery POST GET的值

时间:2012-04-26 14:05:30

标签: jquery json post get

我需要从服务器上使用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',
      }
    );
  });
})

1 个答案:

答案 0 :(得分: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',
          }
        );
      }
    );
  });
})