2016-11-29 10 views
0

저는이 주제에 대해 많은 시간을 할애하여 고심하고 있습니다.타이머와 포스트 아약스 요청 사이에 객체 전달하기 (익명 함수)

&.post (WordPress 처리 AJAX) 요청에 개체를 전달해야하지만 일반 변수를 사용하여 올바르게 처리하는 방법을 알 수 없습니다. 대신, 나는 $ (document)를 호출하고 DOM 엘리먼트를 반복해야한다. (매우 추하고 느리다).

$(document).find('#sections_title').val() request을 사용하는 대신 게시물 변수에 제목 변수를 모두 전달할 수 있도록이 코드를 어떻게 수정합니까?

올바르게 수행하는 방법을 알려주십시오.

(function ($) { 
    var title = $('#sections_title'); 
    var timeout = 2000; 

    var delay = (function() { 
     var timer = 0; 

     return function (callback, ms) { 
      clearTimeout(timer); 
      timer = setTimeout(callback, ms); 
     }; 
    })(); 

    title.keyup(function() { 

     // i would like to have variable here, that grabs the $(this).val() 
     // and use this variable to pass to the data 
     // var value = ....... 

     delay(function() { 
      $.post(
       ajaxurl, 
       { 
        'action': 'add_foobar', 
        'data': $(document).find('#sections_title').val() 
        // instead I would like: 
        // 'data': value 
       }, 
       function(response){ 
        alert('The server responded: ' + response); 
       } 
      ); 

     }, timeout); 
    })(); 
})(jQuery); 

답변

1

이것은 가장 쉬운 방법입니다. val을 콜백 객체로 바인딩합니다. 그런 다음 사용해야 할 때 이것을 문자열로 변환하십시오. 여기

delay(function() { 
     $.post(
      ajaxurl, 
      { 
       'action': 'add_foobar', 
       'data': String(this) 
       // instead I would like: 
       // 'data': value 
      }, 
      function(response){ 
       alert('The server responded: ' + response); 
      } 
     ); 

    }.bind(Object($(this).val())), timeout); 

또는 전체 코드

(function ($) { 
    var title = $('#sections_title'); 
    var timeout = 2000; 

    var delay = (function() { 
     var timer = 0; 

     return function (callback, ms) { 
      clearTimeout(timer); 
      timer = setTimeout(callback, ms); 
     }; 
    })(); 

    title.keyup(function() { 

     // i would like to have variable here, that grabs the $(this).val() 
     // and use this variable to pass to the data 
     // var value = ....... 

     delay(function() { 
      $.post(
       ajaxurl, 
       { 
        'action': 'add_foobar', 
        'data': String(this) 
        // instead I would like: 
        // 'data': value 
       }, 
       function(response){ 
        alert('The server responded: ' + response); 
       } 
      ); 

     }.bind(Object($(this).val())), timeout); 
    })(); 
})(jQuery); 
+0

이것은 내가 사용했던 것이다. 하지만 한 가지 질문이 있습니다. 텍스트를 개체로 변환하는 이유는 무엇입니까? 바인딩에서 'this'를 전달하고 지연 함수 내에서 전체 jquery 객체를 추출했습니다. – HelpNeeder

+0

@HelpNeeder 그것도 작동합니다. 그러나 값이 필요하기 때문에 요소 또는 jquery 객체에 대한 참조를 만들고 싶지 않았습니다. 이 객체에 String 프로토 타입 멤버가 없으므로 값을 Object로 변환했습니다. 권투를 위해서만 –

+0

아! 글쎄, 나는 단지 가치가 필요한 상태라고 했어. 그래도 값을 전달하는 다른 방법에 감사드립니다. 대단히 고마워! – HelpNeeder

1

window object에 명시 적으로 설정할 수 있습니다. 브라우저에서 전역 개체는 node.js과 같은 특정 환경을 제외하고는 창 개체와 동일합니다.

(function($) { 
    window.title = $('#sections_title'); 
    var timeout = 2000; 

    var delay = (function() { 
     var timer = 0; 

     return function(callback, ms) { 
      clearTimeout(timer); 
      timer = setTimeout(callback, ms); 
     }; 
    })(); 

    title.keyup(function() {  
     delay(function() { 
      $.post(
       ajaxurl, { 
        'action': 'add_foobar', 
        'data': window.title 
       }, 
       function(response) { 
        alert('The server responded: ' + response); 
       } 
      ); 

     }, timeout); 
    })(); 
})(jQuery); 
+0

이 좋은 해결책이지만 다른 JS 코드와의 충돌을 만들 수 있기 때문에 나는 이것을 사용하지 않을 것입니다. 그러나 나는 그 아이디어를 좋아한다. 감사! – HelpNeeder