2017-02-18 48 views
0

我正在使用jQueryUI autocomplete如何通过更多数据自动完成ajax

这是我与各自的品牌信息产品 (Laravel关系/ SQL连接)的数据

[ 
    { 
    "id": 2, <--------- product.id 
    "name": "iphone", <--------- product.name 
    "created_at": "2017-02-08 06:12:34", 
    "updated_at": "2017-02-08 06:12:34", 
    "user_id": 1, 
    "brand_id": 1, 
    "ms_url": "google.com", 
    "gravity": 1.03, 
    "example_id": null, 
    "relevance": 210, 
    "brand": { 
     "id": 1, 
     "name": "apple",<--------- product.brand.name 
     "created_at": "2017-02-08 03:00:49", 
     "updated_at": "2017-02-08 03:00:49", 
     "user_id": 1, 
     "abbreviation": "AP", 
     "visible": 1 
    } 
    } 
] 

这是()选项自动完成ajax的一部分。我想它 用品牌填写输入,然后填写产品名称。

source: function(request, response) { 
    $.ajax({ 
     type: "GET", 
     url: "/find", 
     dataType: "json", 
     data: { 
     term: request.term 
     }, 
     error: function(xhr, textStatus, errorThrown) { 
     alert('Error: ' + xhr.responseText); 
     }, 
     success: function(data) { 
     console.log('data: ' + data.brand.name + ' - ' + data.name); 
     //Outputs: apple - iphone 
     response($.map(data, function(product) { 
      return { 
      label: product.brand.name + " " + product.name, 
      value: product.brand.name + " - " + product.name 
      }; 
     })) 
     } 
    }); 
    }, 
    select: function(event, ui) { 
    console.log(ui); 
    //only conains product.brand.name & product.name, I need product.id 

    // $(this).data('prod-id', ui.id); 

    } 

问题:我如何也通过product.id这样我就可以把它添加到我的输入数据属性?我已经动态地添加了输入,并且希望在提交到数据库之前检查后端的产品ID,而不是检查输入值。

电流输入

<input type="text" class="ui-autocomplete-input" data-prod-id="" value="apple - iphone"> 

输入

<input type="text" class="ui-autocomplete-input" data-prod-id="2" value="apple - iphone"> 

回答

0

的期望输出的输出可以采取“价值”和“标签”键不同的值,那么在选择活动的时间分配值。

例子:

source: function(request, response) { 
    $.ajax({ 
     type: "GET", 
     url: "/find", 
     dataType: "json", 
     data: { 
     term: request.term 
     }, 
     error: function(xhr, textStatus, errorThrown) { 
     alert('Error: ' + xhr.responseText); 
     }, 
     success: function(data) { 
     console.log('data: ' + data.brand.name + ' - ' + data.name); 
     //Outputs: apple - iphone 
     response($.map(data, function(product) { 
      return { 
      label: product.brand.name + " - " + product.name, 
      value: product.id //<---------- assign product id 
      }; 
     })) 
     } 
    }); 
    }, 
    select: function(event, ui) { 
    $(this).val(ui.item.label); //<----------- assign value of lable 

    $(this).attr('data-prod-id', ui.item.value); //<------data-prod-id 
    return false; //<------------ to prevent from assign original value 

    } 
0

我结束了这种方法去。看起来你必须指定至少一个标签或一个值。所以只要你设置其中一个,你可以在数组中添加额外的必要项目。

response($.map(data, function(product) { 
    return { 
    id: product.id, 
    title: product.brand.name + " - " + product.name, 
    value: product.brand.name + " " + product.name 
    }; 
}))