2012-08-13 2 views
1

보통 2 ~ 4 초가 걸리며 작업하는 데 너무 오래 걸리는 것처럼 보입니다.왜이 AJAX 호출이 오래 걸리나요?

$("#IngTable").html("<center><img src=../img/loading.gif /></center>"); 

    var search = document.getElementById("IngSearch").value; 
    var apiLink = "/API/Ingredient/Search?search=" + search; 
    $.ajaxSetup({ accepts: "application/json" }); 
    $.ajax({ 
     url: apiLink, 
     type: "GET", 
     success: function(data) { 
      var ingredients = JSON.parse(data); 
      var htmlIngred = ""; 
      for (var i = 0; i < ingredients.length; i++) { 
       htmlIngred += "<tbody><td><span>" + ingredients[i].Name + "</span></td><td><a class='btn btn-success btn-mini' onclick='addIngred(" + ingredients[i].IngredientId + ");'>Add</a></td></tbody>"; 
      } 
      document.getElementById("IngTable").innerHTML = htmlIngred; 
     }, 
     error: function (a, b, c) { } 
    }); 

그리고 여기에 웹 API 컨트롤러 : 다음은 AJAX입니다

[HttpGet] 
    public string IngredientSearch(string search) 
    { 
     var sw = Stopwatch.StartNew(); 
     var db = new Glubee.Model.GlubeeEntities(); 
     var results = db.Ingredients.Where(x => x.Name.Contains(search)).ToArray(); 
     sw.Stop(); 
     return JsonConvert.SerializeObject(results); 
    } 

성분 표에서 16 일이 각각 긴에는 20 개 이상의 문자를 인하지 있습니다.

문제가 너무 오래 걸릴 수있는 사람이 있습니까?

편집 : 정확히 아직 느린 무엇

public class RouteConfig 
{ 
    public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 

     routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 
    } 
} 
+0

데이터베이스에 프로파일 러를 넣고 SQL 실행을 확인하십시오. – benPearce

+0

IngredientSearch가 너무 오래 걸리는 것입니까? – rikitikitik

+0

@benPearce IngredientSearch 함수의 시작과 끝 부분에 스톱워치를 넣고 30-100ms 사이에 도착합니다. 대부분 40ms에 가깝기 때문에 문제는 그 함수에 있다고 생각하지 않습니다. – Kyle

답변

6

당신이 식별 한 : 그것은 도움이 될 것입니다 경우 여기 내 Global.asax.cs 페이지는 다음과 같습니다 내 RouteConfig 여기

public class MvcApplication : System.Web.HttpApplication 
{ 
    protected void Application_Start() 
    { 
     AreaRegistration.RegisterAllAreas(); 

     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
     BundleConfig.RegisterBundles(BundleTable.Bundles); 
    } 

그리고 무엇입니까?

예 : 당신의 IngredientSearch 방법으로, 경우에 당신은 아직 시간이 오래 걸릴 않습니다

[HttpGet] 
public string IngredientSearch(string search) 
{ 
    return String.Empty; 
} 

[HttpGet] 
public string IngredientSearch(string search) 
{ 
    var sw = Stopwatch.StartNew(); 
    var db = new Glubee.Model.GlubeeEntities(); 
    var results = db.Ingredients.Where(x => x.Name.Contains(search)).ToArray(); 
    sw.Stop(); 
    return JsonConvert.SerializeObject(results); 
} 

의 코드를 변경?

만약 그렇다면; 스크립트 라이브러리 문제를 살펴 보겠습니다. 그렇지 않다면 그것은 잘못 된 DB 레이어입니다.

이와 같은 버그는 흔히 추적하기가 힘들 기 때문에 을 잊어 버리고 비트별로 문제를 테스트해야합니다. 위와 같은 변경으로 인해 많은 문제가 제거되었으므로 약간의 노력만으로 큰 단서를 얻을 수 있습니다.

추신 : 죄송합니다.이 답변이 아닙니다. 하지만 코드 변경을 명확하게 강조 할 수 있도록 게시하고 싶습니다. 제발 투표하지 마세요!

+0

위의 변경으로 인해 자바 스크립트에 문제가 발생할 수 있다는 것을 알고 있습니다. 문제는 실제로이다; 이것에 의해 야기 된 자바 에러는 청어입니다. –

+0

귀하의 조언에 따라 나는 문제를 추적 할 수있었습니다. JSON에 직렬화 및 전후 처리 모두에서 오랜 시간이 걸렸습니다. 왜냐하면 나에게 알지 못하기 때문에, 내가 원했던 '재료'를 얻고 직렬화하는 것이 아니라 그림과 관련된 모든 테이블의 모든 것을 직렬화하는 것이 었습니다. 되돌아 보면 이해가 가며 혼란 스러움에 대해 설명합니다. 결과를 얻는 데 걸리는 시간은 매우 길었고 매우 빨랐습니다. 반환되기 전에 일련 번호를 지정하는 것은 스톱워치 시간에 포함되지 않았습니다. 도움 주셔서 감사합니다. – Kyle

+0

결과에 포함 된 나머지 부분없이 이름과 ID가 필요한 개체의 목록을 만들기 위해이 개체를 다시 작성하면 거의 순간적으로 느껴집니다. 감사합니다. – Kyle

관련 문제