如何将值从Ajax响应对象传递给元素

时间:2016-11-29 01:30:01

标签: javascript jquery ajax

我的ajax功能正常。它从数据库中检索多个对象。全部都是supplier_namesupplier_idresponse对象将它们放在页面上的正确元素中。

问题:当您点击其中一个选项时,如何将supplier_id放入隐藏元素?

 $('#supplier_name').autocomplete({
    minLength: 3,
    source: function (request, response, term) {

        var param = request.term;
        $.ajax({
            url: "supplier_search/" + param,  
            dataType: "json",
            type: "GET",
            success: function (data) {

                response($.map(data, function(item) {
                       return item.supplier_name;
                    }

                ));

          //      $("#supplier_search").val(item.supplier_name);  THIS DOES NOT WORK
         //       $("#supplier_id").val(item.id);


            },//END Success
        });//END AJAX
    },

}); 

HTML

<div class="col-sm-4 col-md-4"><input class="form-control" placeholder="Type first 3 digits of name" name="supplier_name" type="text" id="supplier_name"></div>
    <input id="supplier_id" name="supplier_id" type="hidden">

2 个答案:

答案 0 :(得分:0)

这是我的代码:

我有一个标签<select id='cms_target2' name='cms_target2' onchange='javascript:cxChangeDept(2, this.value)' style='width:150px;'>

和我的javascript:

function cxChangeDept(level, val)
{

        var data = {
            level: level + 1,
            dept_code: val,
            type: "GET_DEPT"
        };
        cxGetData(data);
}

    function cxGetData(data)
    {
    $.ajax({
        url: "index",
        type: "POST",
        data: data,
        dataType: "json",
        success: function (data) {
            cxGetDataOK(data);
        }
    });
}

    function cxGetDataOK(data)
    {


     //do somthing with your data
}

答案 1 :(得分:0)

function cxGetDataOK(data){
  $('#supplier_search').val(data.supplier_name);
  $('#supplier_id').val(data.id);
}