2013-04-25 31 views
3

下面的Ajax調用包裝在jQuery自動完成source函數中。檢查Fiddler以及Chrome的網絡控制檯中的返回值,我可以看到數據正在以正確的格式返回到視圖。jQuery自動完成不顯示從Ajax調用返回的數據

但是,用戶開始鍵入時出現的正常項目列表不會顯示。你可以按照你想要的那樣儘可能快/慢地鍵入,並且不會出現任何內容。

我在控制器方法(這是一個ASP MVC站點)中設置了一個斷點,以確保程序的一部分正常運行,並且每次都會觸發。

我只是幾個星期的新jQuery,所以任何幫助將不勝感激。謝謝!

$(function() { 
    $('#DRMCompanyId').autocomplete({ 
     source: function (request, response) { 
      $.ajax({ 
       url: '@Url.Action("compSearch", "AgentTransmission")', 
       type: 'GET', 
       dataType: 'json', 
       data: request, 
       success: function (data) { 
         alert(data); 
         response($.map(function (value, key) { 
          alert(value); 
         return { 
          label: value, 
          value: key 
         }; 
        })); 
       } 
      }); 
     }, 
     minLength: 1 
    }); 
}); 

編輯

我增加了幾個alerts的代碼。 alert(data)將會啓動,但alert(value)不會。

下面是從Chrome的調試控制檯

enter image description here

返回json的副本,這裏是返回一個Dictionary對象的形式的鍵/值對的控制器的方法。

  XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable); 
      nsmgr.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"); 
      nsmgr.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices"); 

      Dictionary<string, string> companies = new Dictionary<string, string>(); 

      foreach (XmlNode childNode in parentNode) 
      { 
       if (!String.IsNullOrWhiteSpace(childNode["content"].InnerText)) 
       { 
        try 
        { 
         string name = childNode["title"].InnerText; 
         string id = childNode["content"].InnerText.Substring(0, 6); 

         companies.Add(id, name); 
        } 
        catch (Exception ex) 
        { 

        } 
       } 
      } 

      return Json(companies, JsonRequestBehavior.AllowGet); 
     } 
     catch (Exception ex) 
     { 
      results = ex.InnerException.ToString(); 
     } 

     return Json(results, JsonRequestBehavior.AllowGet); 
+0

你能展示你的json嗎? – 2013-04-25 19:47:02

+0

你的意思是返回的值或它在控制器中的設置? – NealR 2013-04-25 19:52:40

+0

我的意思是返回json .. – 2013-04-25 19:54:28

回答

1

的$ .MAP函數需要一個數組/對象枚舉,作爲第一個參數。參考號jQuery.map

嘗試改變

$.map(function (value, key) { 

$.map(data, function (value, key) { 

問候。

0

jQuery的文檔:http://api.jquery.com/jQuery.map/說,$.map函數需要兩個參數;第一個是一個數組。我認爲你需要使用$.each方法。

我也相信在這種情況下,response是一個回調函數,您應該使用AJAX中的數據作爲參數調用,如response(data)

從這裏臀部射擊,我認爲你的成功處理程序應該是大約是這樣的:

  success: function (data) { 
        var x, array = []; 
        for(x in data) { 
         array.push({ 
          label: data[x].value, 
          value: data[x].key  
         }; 
        } 
        response(data); 
      }