我需要使用ajax返回id和名称的jQuery Autocomplete示例
我需要一个示例,说明如何编写jQuery自动完成以填充product_id,同时显示product_name调用ajax页面“remote.php”
remote.php: $ partial = addslashes($ _ POST ['partial_search']); $ myDataRows = array(); $ result = mysql_query(“SELECT product_id,product_name FROM products WHERE product_name like”%$ partial%“); while($ row = mysql_fetch_row($ result)){array_push($ myDataRows,$ row);} $ ret = json_encode( $ myDataRows); echo $ ret;
我不知道如何编写jQuery自动完成代码,如果我需要更改remote.php
谢谢
加上以后:
我找到了另一个解决方案:
function nqi_search(type,id_name,text_name) { $(“#”+ text_name).autocomplete({ 来源:“remote.php?&t =”+类型, minLength:1, select:function(event,ui){ $(“#”+ id_name).val(ui.item.id); } }); } jQuery(document).ready(function(){ nqi_search(“product_search”,“product_id”,“product_name”); //你也可以在一个页面上有很多: nqi_search(“vendor_search”,“vendor_id”,“vendor_name”); });
有一个问题。 如果将nqi_search函数放入.js文件中,它似乎不起作用。 我不知道为什么?
我是这样做的:
请注意,我编写了一个特殊function,其中json可以将项目标记为消息,这样您就可以将消息放入列表中(例如,我为长列表添加了“添加X项未显示”)。 要使用消息function,但标签字段中的文本和消息字段的true布尔值。
要在我刚才拥有的页面上使用它
setupAutocomplete(,);
$.ajaxSetup({ type: "POST", contentType: "application/json; charset=utf-8", data: "{}", dataFilter: function(data) { var msg; if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function') msg = JSON.parse(data); else msg = eval('(' + data + ')'); if (msg.hasOwnProperty('d')) return msg.d; else return msg; }, error: function(msg) { $('#error').html(msg.responseText) } }); // remove this to get rid of custom message handling $.widget("custom.redcomplete", $.ui.autocomplete, { _renderMenu: function(ul, items) { var self = this; $.each(items, function(index, item) { if (item.message) ul.append(" " + item.label + " "); else self._renderItem(ul, item) }); } function setupAutocomplete(inID, inURL) { var myTB = $("[id$='_" + inID + "']"); // change redcomplete to autocomplete to get rid of message handling myTB.redcomplete({ source: function(request, response) { $.ajax({ url: inURL, data: "{'filter': '" + request.term + "'}", success: function(data) { response($.map(data, function(item) { return { label: item.text, value: item.id, // remove this line and the , above to get rid of message handling message: item.message }; })); } }) }, delay: 500, minLength: 3, focus: function(event, ui) { myTB.val(ui.item.label); return false; }, select: function(event, ui) { // action for the select here. return false; }, open: function() { $(this).removeClass("ui-corner-all").addClass("ui-corner-top"); }, close: function() { $(this).removeClass("ui-corner-top").addClass("ui-corner-all"); } });