자동 완성 요청 / 서버 응답은 어떻게 생겼습니까?
이것은 블랙홀 인 것 같습니다. jQuery UI 웹 사이트, Stack Overflow 및 인터넷 검색 을 검색 한 지 한 시간이 지난 후에도 AutoComplete 의 서버 측 작성 방법에 대한 가장 기본적인 정보를 아직 찾지 못했습니다 .
서버에 전달되는 매개 변수는 무엇이며 JSON 응답은 어떻게 표시되어야합니까?
다른 모든 사람들이 어떻게이 방법을 배웠기 때문에 나는 뭔가를 놓치고있는 것 같습니다. 사이트는 클라이언트 측 JavaScript 코드 만 논의하고 프로토콜이나 서버 측 예제는 다루지 않는 것 같습니다.
가장 간단한 원격 예제를 작동시키기에 충분합니다.
서버에 전달되는 매개 변수
request.term
(문서에서) 서버 측 코드 로 전달 해야합니다.
현재 텍스트 입력에있는 값을 참조하는 "term"이라는 단일 속성이있는 요청 객체입니다.
기본적으로 autocomplete
코드에는 다음과 같은 내용이 있습니다.
$("#autocomplete").autocomplete({
// request.term needs to be passed up to the server.
source: function(request, response) { ... }
});
그리고 JSON 응답은 어떤 모습이어야합니까?
autocomplete
위젯은 JSON의 배열로 객체를 기대 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 + 자동 완성의 전체적인 좋은 예제입니다).
기본적으로 ajax 요청이 성공하면 수신 된 데이터가 $.map
자동 완성 위젯이 예상하는대로 정규화됩니다 (를 사용하여 ).
도움이되기를 바랍니다.
Andrew Whitaker의 완벽한 답변 외에도 $ .map의 대체 방법은 렌더러를 재정의하는 것 입니다. 그 예는 jQuery UI 데모 페이지에 나와 있습니다.
다음과 같은 JSON 호출을 사용하여이 기능을 사용했습니다.
JSON 응답
{ "Records": [ { "WI_ID": "1", "Project": "ExampleProject", "Work_Item": "ExampleWorkItem", "Purchase_Order": "", "Price": "", "Comments": "", "Quoted_Hours": "", "Estimated_Hours": "", "Achieved": "False", "Used_Hours": "0" } ] }
jQuery
$("#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 자동 완성에 대한 주요 이해는 성공 익명 함수입니다. AutoComplete의 성공 콜백으로 인해 서버 측 JSON 응답 형식을 활용 / 제어 할 수 있습니다. label, value 형식은 따라야 할 좋은 형식이지만 원하는 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 백엔드를 사용한 매우 표준적인 자동 완성 바인딩을 볼 수 있습니다.
AutoComplete 익명 콜백에서 올바르게 매핑하는 한 서버 측에서 원하는 JSON 형식을 반환 할 수 있습니다. 레이블, 값 이름 값 쌍은 대부분의 요구 사항에 충분하지만 JSON으로 서버 측에서 수행하는 것처럼 AutoComplete 성공 콜백에서 올바르게 매핑합니다.
jQuery UI 자동 완성을 사용하기 위해 서버 측 스크립트를 조정할 필요 가 없습니다 . JavaScript 함수를로 지정하여 source
사용자 지정 요청을 생성하고 (예 : 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
<!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>
다음 자동 완성은 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>
참고 URL : https://stackoverflow.com/questions/5077409/what-does-autocomplete-request-server-response-look-like
'IT TIP' 카테고리의 다른 글
Google Maps API를 사용한 주소 확인 (0) | 2020.11.27 |
---|---|
Subversion에서 원본 파일 [커밋] 타임 스탬프를 유지하려면 어떻게해야합니까? (0) | 2020.11.27 |
기본적으로`git commit -v` (0) | 2020.11.27 |
maven : 명령 줄 옵션을 통해 일부 프로젝트에서 테스트를 건너 뛰려면 어떻게해야합니까? (0) | 2020.11.27 |
git show / git diff에서 tabwidth를 4로 설정 (0) | 2020.11.27 |