0

ajax 호출 (필요한 JSON을 제공함)이 성공하면 트리거 된 함수에서 underscore.js를 사용하여 템플릿을 렌더링하려고합니다. AJAX 호출이 처음으로 성공하면Underscore.js - 처음에 템플릿이 컴파일되지 않습니다.

  • , 나는이 오류가 :

    나는 이상한 행동의 어떤 종류를 겪고있어

Uncaught ReferenceError: response is not defined

  • 가에 대한 성공 두 번째로 페이지를 새로 고침하지 않고 모든 것이 의도 한대로 진행됩니다.

내 JSON이 구조를 가지고 :

{ 
    data: [ 
     item1: {count: "1", url: "http://example1.com", id:"arstd", formatted:"1"}, 
     item2: {count: "53", url: "http://example2.net", id:"hneio", formatted:"0"}, 
     ... 
    ] 
} 

내 underscore.js 템플릿 :

<script type="text/template" id="count_template"> 
    <% _.each (response.data, function (item) { %> 
    <a href="<%- item.url %>"> 
     <li> 
      <p id="<%- item.id %>" class="name"> 
       <%- item.formatted %> 
      </p> 
      <p id="<%- item.id %>_count" class="count"> 
       <%- item.count %> 
      </p> 
     </li> 
    </a> 
    <% }); %> 
</script> 

내 아약스 콜백 기능 :

var on_result_count_fetched = (function() { 
    var totals = $(".regions .count"); 
    var ajax_loader = $("#ajax_loader"); 
    var c_tl = $('#count_template'); 
    var count_div = $('#res_count'); 
    //getting the template for the count response 
    if (c_tl) { 
     var c_template = _.template(c_tl.html()); 
    } 
    _.templateSettings.variable = "response"; 
    //real callback 
    return function (response) { 
     if (response.redirect) { 
      window.location.replace(data.redirect); 
     } else { 
      //hide loading animation 
      ajax_loader.hide(); 
      if (!response && _.isEmpty(response)) { 
       var tmp = $("<button>In case of fail: do this other action!</button>") 
       tmp.click (function() { 
        fetch_results ("searx"); 
       }); 
      } else { 
       console.log(response); 
       var tmp = c_template(response); 
      } 
      count_div.empty(); 
      count_div.append(tmp); 
     } 
    } 
}()); 

답변

0

당신이 _.template(some_string), 밑줄 말의 값을 사용합니다.을 사용하여 some_string을 구문 분석 한 후 JavaScript 함수로 변환하십시오. _.template이 컴파일 된 템플릿 함수를 반환하면 _.templateSettings의 내용은 더 이상 중요하지 않습니다.

당신은 이런 종류의 물건을하고있는

는 :

var t = _.template(some_string); 
_.templateSettings.variable = "response"; 

그래서 당신의 _.templateSettings.variable 과제는 _.template 호출에 영향을 너무 늦게 온다.

if (c_tl) { 
    var c_template = _.template(c_tl.html()); 
} 
_.templateSettings.variable = "response"; 

더 같이해야합니다 : 당신은이 _.template를 호출하기 때문에이 이전 _.templateSettings을 조정해야

if (c_tl) { 
    _.templateSettings.variable = "response"; 
    var c_template = _.template(c_tl.html()); 
} 

아니면 아예 _.templateSettings를 건너 뛰고 수는 말 : 호출 할 때

var tmp = c_template({ response: response }); 

템플릿 함수. 다른 서식 파일에서 response을 사용하여 데이터에 액세스해야 할 것으로 예상되지 않는 경우 _.templateSettings을 사용하면 부작용이 발생할 수 있습니다. 정확히 한 곳에서 전체적으로 _.templateSettings을 구성하거나 완전히 혼자두면 더 잘 작동하는 경향이 있습니다.