如何使用返回json的函数格式化jquery ui自动完成?

时间:2012-02-29 07:13:37

标签: javascript jquery json jquery-ui jquery-ui-autocomplete

我有一个函数可以进行AJAX调用并将数据作为JSON返回。

Donor.prototype.GetFriends = function(callback)
{
    $.post(apiUrl + "getfriends",
    {   
        "authentication_code" : this.authcode        
    },
    function(response)
    {
        if (response)
        {
            callback(response.result);
        }        
    }, "json");
}

现在在我的UI中,我有以下内容:

var donor = new Donor();
$("#msg-to").autocomplete({source: function()
   {
      donor.GetFriends(function(response){response.friends.candidates})
   }
});

但这不起作用...... json正在使用firebug返回,但不会显示在autocomplte字段中。

result
    Object { error_state=0, friends={...}, error_msg=""}

error_msg
    ""

error_state
    0

friends
    Object { candidates="[{"follow_id":"3","0":"...","6":"227.jpg"},false]", donors="[{"follow_id":"4","0":"...","6":"224.jpg"},false]"}

candidates
    "[{"follow_id":"3","0":"3","user_id":"227","1":"227","following":"222","2":"222","candidate_id":"61","3":"61","firstname":"Helen","4":"Helen","lastname":"Hunt","5":"Hunt","image":"227.jpg","6":"227.jpg"},{"follow_id":"5","0":"5","user_id":"225","1":"225","following":"222","2":"222","candidate_id":"55","3":"55","firstname":"Test","4":"Test","lastname":"Candidate","5":"Candidate","image":"225.jpg","6":"225.jpg"},{"follow_id":"1","0":"1","user_id":"222","1":"222","following":"226","2":"226","candidate_id":"59","3":"59","firstname":"New","4":"New","lastname":"Candidate","5":"Candidate","image":"226.jpg","6":"226.jpg"},{"follow_id":"6","0":"6","user_id":"222","1":"222","following":"227","2":"227","candidate_id":"61","3":"61","firstname":"Helen","4":"Helen","lastname":"Hunt","5":"Hunt","image":"227.jpg","6":"227.jpg"},false]"

donors
    "[{"follow_id":"4","0":"4","user_id":"224","1":"224","following":"222","2":"222","donor_id":"124","3":"124","firstname":"Just","4":"Just","lastname":"A Donor","5":"A Donor","image":"224.jpg","6":"224.jpg"},{"follow_id":"2","0":"2","user_id":"222","1":"222","following":"224","2":"224","donor_id":"124","3":"124","firstname":"Just","4":"Just","lastname":"A Donor","5":"A Donor","image":"224.jpg","6":"224.jpg"},false]"

返回的json还返回了candidate_id,firstname,lastname和imageUrl,如何在结果中显示这些内容,其中friend_id为值,其他为显示?

提前致谢...

3 个答案:

答案 0 :(得分:1)

一些事情:

  • 您可能需要返回正在创建的阵列才能使用自动完成功能
  • 您还需要确保对象数组具有正确的自动填充键才能使用

自动填充功能正常工作所需的最低密钥是“标签”和“值”。其他密钥可以包含在内,可以在selectchange等活动中提取。

举个例子,我可能会尝试以下内容。调整GetFriends函数以自动使用jQuery提供的requestresponse回调函数,然后将自动完成所需的格式化数据反馈给它们:

Donor.prototype.GetFriends = function(request, response){

    // this is where you can grab your search term, if need be...
    var search_term = request.term;

    $.post(
        apiUrl + "getfriends",
        {"authentication_code" : this.authcode},
        function(data)
        {
            // process your data here into an array that the autocomplete
            // will appreciate...
            var autocomplete_array = [];
            $.each(data.friends.candidates, function(index, candidate)
            {
                autocomplete_array.push(
                {
                    label: candidate.firstname + " " + candidate.lastname,
                    value: candidate.user_id,
                    another_key: candidate.follow_id,
                    and_another: candidate.image
                });
            });

            // now send the array back to the response parameter...
            response(autocomplete_array);
        },
        "json"
    );
};

然后,我将简化自动完成初始化程序参数以包含您的函数:

$("#msg-to").autocomplete({source: donor.GetFriends});

作为附加说明,要获取项目的键,您可以修改自动填充字段,以包含我之前提到的selectchange事件处理程序:

$("#msg-to").autocomplete(
{
    source: donor.GetFriends
    select: function(event, ui){
        alert("You selected: " + ui.item.label);
        // or...
        alert("You selected: " + ui.item.another_key);
    }
});

希望这有帮助,而且我没有类型o! :)

答案 1 :(得分:0)

您必须在回调中使用setter(请参阅我的示例中的第二个source参数)来添加列表。如果使用数组填充自动完成,则数组需要具有label属性的对象。如果这样可行,您也可以添加value属性。

1。)如果您可以在服务器端更新ajax-result的结果,请将结果更改为:

friends
    Object { candidates=Array { Object { "label": "Helen Hunt" }, ... }, donors=... }

然后你的javascript可以是:

var donor = new Donor();
$("#msg-to").autocomplete({
    source: function(request, setter) {
        donor.GetFriends(function(response) {
            // set list
            setter(response.friends.candidates);
        });
    }
});

2.。)如果你无法对ajax结果进行更改,candidates已经是一个数组:

var donor = new Donor();
$("#msg-to").autocomplete({
    source: function(request, setter) {
        donor.GetFriends(function(response) {
            // create autocomplete list
            var list = response.map(function(element) {
                return {
                    label: element.firstname + ' ' + element.lastname
                };
            });
            // set list
            setter(list);
        });
    }
});

3。)否则(如果candidates是一个字符串)[先试试]:

var donor = new Donor();
$("#msg-to").autocomplete({
    source: function(request, setter) {
        donor.GetFriends(function(response) {
            // parse json string
            var jsonresult = $.parseJSON(response);
            // create autocomplete list
            var list = jsonresult.map(function(element) {
                return {
                    label: element.firstname + ' ' + element.lastname
                };
            });
            // set list
            setter(list);
        });
    }
});

答案 2 :(得分:0)

问题是$ .post方法异步工作。因此,当自动完成尝试获取数据时,您的函数会进行POST调用并返回空结果。要解决此问题,请尝试在.post调用中添加“async:false”选项或:

Donor.prototype.GetFriends = function(callback) {
  $.ajaxSetup({async:false});
  $.post(apiUrl + "getfriends",
  {   
    "authentication_code" : this.authcode        
  },
  function(response)
  {
    if (response)
    {
        callback(response.result);
    }        
  }, "json");
}​