2011-01-09 1 views
3

Jquery UI의 자동 완성 (v1.8.5)을 살펴보면서 추가 매개 변수를 보내고 다른 입력란을 자동 채우기 위해 여분의 데이터를 촬영할 때 문서가 부족하다는 것을 깨달았습니다. 내가 가지고있는 것은 진실이지만, 그런 해킹처럼 보인다 ... 이것을 개선하는 방법에 관한 어떤 생각?Jquery UI 자동 완성 여분의 매개 변수 및 자동 채우기 - 좌절 된 해결책

 <script type="text/javascript"> 

     var optofirst = { 

      width: 375, 

      // doing "$(this)" here fails 

      source: function(request, response) { 

      // grab the calling element 
      // "$(this)" here works but ya gotta dig to get to the ID 

      var cat = $(this); 
      var callid = cat[0].element.context.id; //digging away 

      $.ajax({ 

       // doing "$(this)" here fails 

       url: "automagic.php", 
       dataType: "json", 
       data: { 
       term : request.term, 

       //send its ID to the php script 
       grab : callid, 
      }, 

      success: function(data) { 
       response($.map(data, function(item) { 
       return { 

       // start assigning item handles to the response 

       label: item.first, 
       value: item.first, 
       last: item.last, 
       } 
       })); 
      } 
      }); 
     }, 
      select: function(event, ui) { 
       console.log(ui.item ? 
       "Selected: " + ui.item.last : 
       "Nothing selected, input was " + this.value); 

       // make #lname have the value last name 
       // the "item" in this case appears to get its info from the handles assign in "success:" 

       $("#flyover #lname").attr("value",ui.item.last); 
      }, 
     minLength: 2, 
     }; 

     $("#flyover #fname").autocomplete(optofirst); 

     </script> 

답변

1

일반적인 생각은 나에게 잘 어울립니다. 코드가 jQueryUI's custom data and display demo에 매우 가깝습니다.

당신이 개선 할 수있는 몇 가지 생각이 있습니다 : 자바 스크립트에서 this 객체 리터럴에서 이해가되지 않기 때문에 옵션 내부

  1. // doing "$(this)" here fails 모두

    은, 자동 완성 및 AJAX 호출에 대해 반대; 함수 호출의 컨텍스트를 포함합니다 (this의 큰 설명은 this question 참조).
  2. source 함수 내에서 this이 작동하기 때문에 작동합니다. this에 컨텍스트가 있습니다.

    var callid = cat[0].element.context.id; //digging away 
    

    당신은 쓸 수 : 대신

  3. 이 경우 this 이미 jQuery를 객체이기 때문에

    var calid = this.element.attr('id'); 
    

    이입니다. $(this)은 중복됩니다. 또한, element 숙박 시설에는 jQuery를 개체입니다, 그래서 당신은 단지 attr()

나머지는 나에게 좋아 보인다 사용하여 id에 액세스 할 수 있습니다. 제가 언급 한 데모를보십시오 - 당신이 성취하고자하는 것과 비슷한 것을합니다.

+0

감사 앤드류를 사용하여 레일 3.1에서이 작업을 수행하고 싶어! 실제로 도움이되었습니다. 아약스 호출에 중괄호 안에 "this"를 포함하는 방법을 생각하지 않았습니다. 함수 호출이 아니라 개체 리터럴에서 말하는 것입니다. 매우 감사! 귀하의 "this.element.attr ('id');" 잘 일 했어! 너 락! – eSteimann

2

원본 속성을 사용할 수 있습니다. URL 대신 함수를 설정하십시오. url을 편집하고 서버에 보낼 사용자 정의 등록 정보의 수만큼 customData 행을 바꿔야합니다. 예를 들어 는 :

 $(this).autocomplete({ 
      source: function(request, response) { 
       $.ajax({ 
        url: 'data.php', 
        dataType: "json", 
        data: { 
        term : request.term, 
        customData : $('#something').val() 
        }, 
        success: function(data) { 
        response(data); 
        } 
       }); 
      }, 
      minLength: 3}, { 

     });