2011-01-27 58 views
0

我有下面的腳本似乎不工作。 aspx頁面返回類似json的腳本,在下面的腳本中已經被註釋掉了。如果我將這個json直接粘貼到源數組中,它就可以很好地工作。使用asp.net生成json的自動完成

但是,當我嘗試使用下面的腳本時,我沒有收到任何錯誤消息或任何內容,當我輸入自動填充字段時沒有任何反應。

$(document).ready(function(){ 
    $('#button').click(function() { 
     alert($("#txtAllowSearchID").val()); 
    }); 

    //var $local_source = [ {id:0,value:"c++"}, {id:1,value:"java"}, {id:2,value:"php"}, {id:3,value:"coldfusion"}, {id:4,value:"javascript"}, {id:5,value:"asp"}, {id:6,value:"ruby"} ]; 

    $("#txtAllowSearch").autocomplete({ 
     source: function(request, response) { 
      $.ajax({ 
       type: "POST", 
       url: "test_array.aspx", 
       data: "{'prefixText': '" + $('#txtAllowSearch').val() + "'}", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       success: function(data) { 
        response(data.d); 
       }, 
       failure: function(errMsg) { 
        $('#errMessage').text(errMsg); 
       } 
      }); 
     }, 
     select: function (event, ui) { 
      $("#txtAllowSearch").val(ui.item.value); // display the selected text 
      $("#txtAllowSearchID").val(ui.item.id); // save selected id to hidden input 
     } 
    }); 
}); 

編輯:我認爲這個問題是在aspx頁面:

objSQLCommand = New SqlCommand("select id, value from table1 where value like '%@prefixText%'", objSQLConnection) 
objSQLCommand.Parameters.Add("@prefixText", SqlDbType.VarChar, 255).Value = "ing" 

回答

1

它看起來對我來說,這個問題可能是信號源功能。當你進行ajax調用時,它是異步完成的。所以,該函數啓動ajax調用並繼續,它不會爲源返回任何內容。

我在加載屏幕時發現了這個。如果我在ajax調用後關閉加載屏幕,加載屏幕將不會出現。我不得不在ajax調用成功和錯誤事件中移動它,使它出現並正確消失。

你的源應該只是到URL

source: "test_array.aspx", 

參考從documentation

的數據源是一個服務器端腳本 返回JSON數據,通過 一個簡單的規定源選項的URL。

+0

如果我只是用th如上所述,如何在.aspx頁面返回json數據之前向.aspx頁面發佈值? – oshirowanen 2011-01-27 14:33:02

2

我相信你必須讓ajax調用的源頭到一個web服務,在你的情況下,它似乎是一個Page Method。所以,如果你在後面的頁面看起來像這樣的代碼有一個函數:

public static List<string> GetData(string prefixText){ } 

您將需要從System.Web.Services命名空間裝點該法[WebMethod]

因此,這將最終看起來像:

using System.Web.Services; 

...

[WebMethod()] 
public static List<string> GetData(string prefixText){ } 

HTH

編輯:你也將需要更新您的Ajax調用這個樣子的來源:

source: 'test_array.aspx/GetData'