簡體   English   中英

通過XML進行JQuery自動完成(動態結果)

[英]JQuery AutoComplete From XML (Dynamic Results)

也許我不理解這個概念(我是AJAX / javascript / Web新手)。 我使用的是JQuery自動完成功能,如果我指定了一個有限的小型項目平面文件(suggestions.xml),該功能就可以正常工作,但是當我使用建議的實際生產數據文件(3 MB)時,該腳本將不起作用完全沒有

因此,我創建了一個Web服務,該服務基於文本框中的字符生成XML,但看來此JQuery不會在每次按鍵時都運行,而僅在首次加載頁面時運行。 顯然,要使該功能有用,它需要在用戶鍵入輸入字段時動態獲取結果。

$(document).ready(function () {
var myArr = [];

$.ajax({
    type: "GET",
    // this line always sends the default text; not what the user is typing
    url: "Suggestions.aspx?searchString=" + $("input#txtSearch").val(),
    dataType: "xml",
    success: parseXml,
    complete: setupAC,
    failure: function (data) {
        alert("XML File could not be found");
    }
});

function parseXml(xml) {
    //find every query value
    $(xml).find("result").each(function () {
        myArr.push({ url: $(this).attr("url"), label: $(this).attr("name") + ' (' + $(this).attr("type").toLowerCase() + ')' });
    });
}

function setupAC() {
    $("input#txtSearch").autocomplete({
        source: myArr,
        minLength: 3,
        select: function (event, ui) {
            $("input#txtSearch").val(ui.item.label);
            window.location.href = ui.item.url;
            //alert(ui.item.url + " - " + ui.item.label);
        }
    });
}

});

在服務器上,我希望看到一些與用戶在搜索框中鍵入的字符相對應的請求,但是卻收到一條消息:

2013-10-18 22:02:04,588 [11] DEBUG baileysoft.mp3cms.Site - QueryString params: [searchString]:'Search'

我的平面建議文件似乎是供JQuery處理的大型文件,並且從未調用過我的Web服務腳本,除非首次加載頁面時。

如果我無法返回數據庫(通過Web服務)以在用戶鍵入內容時獲取建議,那么當用戶在搜索框中鍵入內容時,如何動態生成建議?

好吧,我知道了。

在ASPNET方面; 我創建了一個表單來接收和響應AJAX:

    Response.ContentType = "application/json";
    var term = Request.Form["term"];

    var suggestions = GetSuggestions(term); // Database results
    if (suggestions.Count < 1)
        return;

    var serializer = new JavaScriptSerializer();
    Response.Write(serializer.Serialize(suggestions);

在AJAX方面,我修改了js函數:

    $("input#txtSearch").autocomplete({
       minLength: 3,
       source: function (request, response) {
         $.ajax({
           url: "Suggestions.aspx",
           data: { term: $("input#txtSearch").val() },
           dataType: "json",
           type: "POST",
           success: function (data) {
            response($.map(data, function (obj) {
                return {
                    label: obj.Name,
                    value: obj.Url
                };
            }));
           }
          });
       },
       select: function (event, ui) {
         $("input#txtSearch").val(ui.item.label);
         window.location.href = ui.item.value;
       }
    });

現在一切都按預期進行。

希望這對試圖找出ASPNET的JQuery內容的其他人有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM