如果两个值相等,则从json数据返回一个值

时间:2014-02-21 10:40:03

标签: jquery json

function getusername(userid) {
  $.get('/getRecentSignups', function (data) {

console.log(JSON.stringify(data);

//prints
{"_id":"5306e7fd80b1027ad2653db4","email":"priya@gmial.com","id":"27","password":"priya","signedtime":"2014-02-21 11:15:33"},{"_id":"5306e81880b1027ad2653db5","email":"anju@gmail.com","id":"35","password":"anju","signedtime":"2014-02-21 11:16:00"}]

// userid passing here is 35

    data = data.filter(function(val) {
       return (val.id === userid)
         });
  });
}

在上面的函数getusername()中,我正在传递userid 35

数据打印//打印

    {
  "_id": "5306e7fd80b1027ad2653db4",
  "email": "priya@gmial.com",
  "id": "27",
  "password": "priya",
  "signedtime": "2014-02-21 11:15:33"
},
{
  "_id": "5306e81880b1027ad2653db5",
  "email": "anju@gmail.com",
  "id": "35",
  "password": "anju",
  "signedtime": "2014-02-21 11:16:00"
}]

userid等于data.id时,我必须返回相应的电子邮件吗?

1 个答案:

答案 0 :(得分:1)

首先,你不能从方法中返回一个值,因为它是异步的,你需要使用一个回调模式来解决这个问题,如

function getusername(userid, callback) {
    $.get('/getRecentSignups', function (data) {
        data = data.filter(function (val) {
            return (val.id == userid)
        });
        if (data && data.length) {
            callback(data[0].email);
        } else {
            callback(userid);
        }
    });
}
getusername(35, function (email) {
    //do something
})

请参阅How to return the response from an AJAX call?