programing

자동 완성 요구/서버 응답은 어떻게 되어 있습니까?

linuxpc 2023. 4. 1. 08:31
반응형

자동 완성 요구/서버 응답은 어떻게 되어 있습니까?

이것은 블랙홀인 것 같습니다.jQuery UI 웹사이트, 스택 오버플로 및 구글링을 1시간 동안 검색해도 자동 완성 서버 측 작성 방법에 대한 가장 기본적인 정보를 찾을 수 없습니다.

서버에 전달되는 파라미터와 JSON 응답의 모양은 무엇입니까?

내가 뭔가 놓치고 있는 게 틀림없어. 다른 사람들은 어떻게 이런 걸 배웠지?사이트에서는 클라이언트 측 JavaScript 코드만 논의하며 프로토콜이나 서버 측 예는 논의하지 않습니다.

가장 간단한 원격 예제를 작동시키려면 충분한 시간이 필요합니다.

서버에 전달되는 매개 변수

요.request.term(매뉴얼에서 참조) 서버측 코드로 송신합니다.

"term"이라는 단일 속성을 가진 요청 개체로, 텍스트 입력에 현재 있는 값을 나타냅니다.

기기 your your your autocomplete드음

$("#autocomplete").autocomplete({
    // request.term needs to be passed up to the server.
    source: function(request, response) { ... }
});

JSON 응답은 어떻게 해야 할까요?

autocomplete이 음음음 음음 、 음음sonsonJSON 오브젝트 배열이 합니다.label ★★★★★★★★★★★★★★★★★」value, 「」( 「」)만을 )value을 사용법가장 간단한 경우 다음과 같은 데이터를 반환할 수 있습니다.

[
    { label: 'C++', value: 'C++' }, 
    { label: 'Java', value: 'Java' }
    { label: 'COBOL', value: 'COBOL' }
]

더 것이 한 경우에는 을 하면 .success$.ajax자동 완성이 데이터를 가져오기 전에 데이터를 정규화하는 함수:

source: function( request, response ) {
    $.ajax({
        /* Snip */
        success: function(data) {
            response($.map( data.geonames, function( item ) {
                return {
                    label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                    value: item.name
                }
            }));
         }
    });

이 코드는 이 에서 따온 것입니다(이것은 보다 복잡한 시나리오에서 ajax + autocomplete works의 전체적인 좋은 예입니다).

됩니다(「Ajax」를 사용하여$.map자동완성 위젯이 기대하는 것을 나타냅니다.

Andrew Whitaker의 완벽한 답변과 더불어 $.map의 다른 방법은 렌더러(jQuery UI Demo 페이지에 표시된 )를 재정의하는 예시는 jQuery UI Demo 페이지에 나와 있습니다.

JSON 콜을 사용하여 다음과 같은 기능을 사용하고 있습니다.

JSON 응답

{
   "Records": [
       {
           "WI_ID": "1",
           "Project": "ExampleProject",
           "Work_Item": "ExampleWorkItem",
           "Purchase_Order": "",
           "Price": "",
           "Comments": "",
           "Quoted_Hours": "",
           "Estimated_Hours": "",
           "Achieved": "False",
           "Used_Hours": "0"
       }
   ]
}

j쿼리

$("#WorkItem").autocomplete({
      source: function(request, response){
           $.ajax({
               type: "POST",
               url: "ASPWebServiceURL.asmx/WorkItems",
               data: "{'Project_ID':'1'}",
               contentType: "application/json; charset=utf-8",
               dataType: "json",
               success: function (msg) {
                   response($.parseJSON(msg.d).Records);
               },
               error: function (msg) {
                   alert(msg.status + ' ' + msg.statusText);
               }
           })
       },

       select: function (event, ui) {
           $("#WorkItem").val(ui.item.Work_Item);
           return false;
       }
})
.data("autocomplete")._renderItem = function (ul, item) {
    return $("<li></li>")
    .data("item.autocomplete", item)
    .append("<a>" + item.Work_Item + "</a>")
    .appendTo(ul);
};

이 예에서는 _renderItem 함수가 덮어쓰기되어 검색 결과 목록(텍스트 상자 아래에 표시되는 목록)이 JSON 응답에서 가져온 레코드의 속성을 사용하여 채워집니다.

단순하지는 않지만 매우 흥미로운 작업을 수행할 수 있습니다(예: JSON 응답의 여러 비트 데이터 사용).

지금까지의 답변은 모두 복잡하고 오해의 소지가 있습니다.jQuery UI Auto Complete의 주요 이해는 success anonymous 함수입니다.Auto Complete의 성공 콜백으로 인해 서버 측 JSON 응답 형식을 활용/제어할 수 있습니다.라벨, 값 형식은 따르는 것이 좋지만 원하는 JSON 형식을 정의할 수 있습니다. 핵심은 성공 함수를 정의하는 방법입니다.

 <input id="refPaymentTerms" class="form-control">

$("#refPaymentTerms").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        url: "/admin/JobPaymentRefs",
                        dataType: "json",
                        data: {
                            term: request.termCode
                        },
                        error: function (xhr, textStatus, errorThrown) {
                            alert('Error: ' + xhr.responseText);
                        },
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item.label,
                                    value: item.value
                                }
                            }));
                        }
                    });
                }
            });

MVC 컨트롤러:

public JsonResult JobPaymentRefs()
    {
        var query = from REFTerm in _db.REFTerms
                     select new
                    {
                        label = REFTerm.TermCode,
                        value = REFTerm.TermCode
                    };
        //var refTerms = _db.REFTerms.Select(x => x.TermCode);

        return Json(query.ToArray());
    }

ASP와의 자동 완전 바인드는 매우 표준적입니다.NET 백엔드

자동 완성 익명 콜백에서 올바르게 매핑되어 있는 한, 서버 측에서 원하는 JSON 형식을 반환할 수 있습니다.라벨과 값 이름 값의 쌍은 대부분의 요건에 적합하지만, JSON을 사용하여 서버 측을 수행하는 것처럼 자동 완성 성공 콜백에 올바르게 매핑하기만 하면 됩니다.

jQuery UI 자동 완료를 사용하기 위해 서버 측 스크립트를 조정할 필요는 없습니다.JavaScript 함수를 로 지정하여 커스텀 요구 작성(POST 또는 GET 사용, 서버 측 스크립트가 기대하는 쿼리 문자열 파라미터 사용) 및 임의의 응답 처리(XML 응답 처리 등)를 할 수 있습니다.

그래도 스트링을 사용할 때는source파라미터, 다음에 나타냅니다.

[...] 자동 완성 플러그인은 해당 문자열이 JSON 데이터를 반환할 URL 리소스를 가리킬 것으로 예상합니다.같은 호스트 또는 다른 호스트(JSONP를 제공해야 함)에 배치할 수 있습니다.Autocomplete 플러그인은 결과를 필터링하지 않고 서버 측 스크립트가 결과를 필터링하기 위해 사용해야 하는 용어 필드가 포함된 쿼리 문자열이 추가됩니다.예를 들어 원본 옵션이 다음과 같이 설정된 경우http://example.com사용자 유형 foo, GET 요청은 다음과 같습니다.http://example.com?term=foo데이터 자체는 위에서 설명한 로컬 데이터와 동일한 형식일 수 있습니다.

"데이터 자체는 위에서 설명한 로컬 데이터와 동일한 형식이 될 수 있습니다."에 대해서는 다음 JSON(또는 JSONP) 형식이 작동합니다.

// no matching entries
[]

// array of strings
[
"Option 1",
"Option 2"
]

// array of objects with label property
[{
    "label": "Option 1"
}, {
    "label": "Option 2"
}]

// array of objects with value property
[{
    "value": "Option 1"
}, {
    "value": "Option 2"
}]

// array of objects with label and value properties
[{
    "label": "Option 1",
    "value": 1
}, {
    "label": "Option 2",
    "value": 2
}]

오브젝트 배열의 경우 라벨 및/또는 기타 속성을 자유롭게 지정할 수 있습니다.value모든 속성은 콜백 내에서 사용할 수 있습니다.

아래의 코드가 나에게 유효합니다.이를 위해서는 json 부호화 데이터가 필요합니다.데이터를 가져오면 jQuery 자동 완성 형식에 따라 데이터를 수정하고 선택도 활성화합니다.

var $url = "http://some-url/get-json";
//name is the id of the textbox where autocomplete needs to be shown
$('#name').autocomplete(
{ 
source: function(request,response)  
{ 

  //gets data from the url in JSON format
  $.get($url, function(data)
  {         
    obj = JSON.parse(data);   //parse the data in JSON (if not already)
    response($.map(obj, function(item)
    {
      return {
        label: item.full_name,
        value: item.full_name,
        id:item.id,
        email:item.email,
        phone:item.phone,
      }
    }
  ));        //end response
});          //end get
},
select:function(event, ui)
{ 
 console.log(ui.item.full_name);
 console.log(ui.item.email);
}   

}); //end of autocomplete

다음 자동완성은 https://jqueryui.com/autocomplete/ #remote-jsonp에서 가져온 것입니다.

데모 링크: https://jqueryui.com/resources/demos/autocomplete/remote-jsonp.html

다음은 소스 코드입니다.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery UI Autocomplete - Remote JSONP datasource</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">
    <style>
    .ui-autocomplete-loading {
        background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat;
    }
    </style>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
    $( function() {
        function log( message ) {
            $( "<div>" ).text( message ).prependTo( "#log" );
            $( "#log" ).scrollTop( 0 );
        }

        $( "#birds" ).autocomplete({
            source: function( request, response ) {
                $.ajax( {
                    url: "search.php",
                    dataType: "jsonp",
                    data: {
                        term: request.term
                    },
                    success: function( data ) {
                        response( data );
                    }
                } );
            },
            minLength: 2,
            select: function( event, ui ) {
                log( "Selected: " + ui.item.value + " aka " + ui.item.id );
            }
        } );
    } );
    </script>
</head>
<body>

<div class="ui-widget">
    <label for="birds">Birds: </label>
    <input id="birds">
</div>

<div class="ui-widget" style="margin-top:2em; font-family:Arial">
    Result:
    <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>


</body>
</html>

<!doctype html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Autocomplete - Categories</title>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
        <link rel="stylesheet" href="/resources/demos/style.css" />
        <style>
            .ui-autocomplete-category {
                font-weight: bold;
                padding: .2em .4em;
                margin: .8em 0 .2em;
                line-height: 1.5;
            }
            body {
                font-family: "Trebuchet MS", "Helvetica", "Arial", "Verdana", "sans-serif";
                font-size: 62.5%;
            }
        </style>
        <script>
            $.widget("custom.catcomplete", $.ui.autocomplete, {
                _renderMenu : function(ul, items) {
                    var that = this, currentCategory = "";
                    $.each(items, function(index, item) {
                        if (item.category != currentCategory) {
                            ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
                            currentCategory = item.category;
                        }
                        that._renderItemData(ul, item);
                    });
                }
            });
        </script>
        <script>
            $(function() {
                $("#search").catcomplete({
                    delay : 0,
                    source : function(request, response) {
                        $.ajax({
                            url : "search",
                            dataType : "json",
                            data :"searchText=hk",
                            success : function(data) {
                                response(data);
                            } //success
                        });
                    }
                });
            });
        </script>
    </head>
    <body>enter code here
        <label for="search">Search: </label>
        <input id="search" />
    </body>
</html>

언급URL : https://stackoverflow.com/questions/5077409/what-does-autocomplete-request-server-response-look-like

반응형