AjaxでURLを指定する際に、そのURLを変数にしたいのですが、うまくいかず悩んでいます。
テキストに入力した値を使用してURLを組み立てたいのですが、
autocompleteメソッドの中で、変数を設定する方法がわかりませんでした。
以下のように、URLを固定で設定した場合は、動作確認できました。
<script type="text/javascript"> $(function () { var pUrl = '/api/aaaaa/ABCDE'; $('#txtKeywd').autocomplete({ source: pUrl, type: "GET", autoFocus: true, delay: 500, minLength: 1, select: function (e, ui) { if (ui.item) { alert(JSON.stringify(ui.item)); } } });
テキストボックス $('#txtKeywd') で入力されている値を、Ajaxのパラメータであるsourceに渡したいのです。
例えばテキストボックスに'あいうえお'と入力したら、'/api/aaaaa/あいうえお'にしたいです。
以下のようにしてみたのですが、サーバー側に届きませんでした。
$('#txtKeywd').autocomplete({ source: '/api/aaaaa/' + $('#txtKeywd').val(),
サーバー側には '/api/aaaaa' のコントローラーが待機しています。
'/api/aaaaa/あいうえお'の あいうえお の部分をパラメータで受け取るようにしています。
sourceに変数を渡す方法を教えていただきたいです。
よろしくお願いします。
追記:ネットワーク覗きました。
[1]以下の場合
・source: '/api/aaaaa/abcde'
・テキスト入力値を hhhhh にした場合
⇒https://localhost/api/aaaaa/abcde?term=hhhhh
[2] ・source: '/api/aaaaa' ・テキスト入力値を hhhhh にした場合
https://localhost/api/aaaaa?term=hhhhh
でした。仕様もわからず使ってました・・・m(__)m
追記:実現できました。ありがとうございました。参考までにソースを記載します。
#クライアント側 <!-- jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- jQuery UI --> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <script> $('#txtKeywd').autocomplete({ source: '/api/aaaaa', autoFocus: true, delay: 500, minLength: 1, select: function (e, ui) { if (ui.item) { alert($('#txtKeywd').val()); alert(JSON.stringify(ui.item)); $('#detail').html(ui.item.detail); } } }); </script> <input id="txtKeywd" type="search" size="20" maxlengh="50" /> <span id="detail"></span> #サーバー側 [Route("api/[controller]")] [ApiController] public class AaaaaController : ControllerBase { // GET: api/aaaaa ★こっちで受け取る [HttpGet] public string Get() { string aaa = Request.Query["term"]; Debug.WriteLine(aaa); ・・・・・ // 戻り値はjson文字列 return "[{"label":"LABEL1","value":"VALUE1","detail":"DETAIL1"},{"label":"LABEL2","value":"VALUE2","detail":"DETAIL2"},{"label":"LABEL3","value":"VALUE3","detail":"DETAIL3"}]"; } // GET: api/aaaaa/5 [HttpGet("{abcde}", Name = "Get")] public string Get(string abcde) { Debug.WriteLine(abcde); ・・・・・ } } #ネットワークのなかみ https://localhost/api/aaaaa?term=hhhhh
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/05/13 03:12
2020/05/13 03:29