Equivalent of %QUERY
when using POST within Bloodhound's remote is query
.
Here is a simple example (with detailed explanation) where you can use it for both GET
and POST
. As you can see I have declared a variable isExtendUrl
. If this is set to true
then the query (what you type) will be added to the end of the url (you have to give the myurl
somehow).
The next variable is isRequestMethod
. If this is set to POST
, you can use bloodhound for POST
calls else you can use it for GET
calls. As you can see prepare
function has two parameters query
and setting
. query
is the one what you type. If you just want the POST
call without GET
move prepare
key value pair inside remote
object.
So, if you have to use JSON
body as {gender: 'MALE', name: 'what is typed'}
for your POST
call. You can have an initial query object with all your key value pairs eg: initialQuery = {gender: 'MALE'}
, and the key searchKey
which should be added to initialQuery
when searching, could be added on prepare
like initialQuery[searchKey] = query
.
Finally, if the response object of your POST
call is an object and you have to extract a specific key value use filter
. Eg: Say your response object is
{
status: 'some status',
content: [{array}, {of}, {objects}, ...],
someKey: someValue
}
and you have to get content
, then return data.content
. Here is a full example
let isExtendUrl = true; //to add query at the end of the url, usually used with GET
let isRequestMethod = 'POST';
let initialQuery = {gender: 'MALE'};
let searchKey = 'name';
let bloodhound = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: isExtendUrl ? myurl + '%QUERY' : myurl,
wildcard: '%QUERY',
filter: function (data) {
return $.map(data.content, function (obj) {
return obj;
});
}
}
});
if (isRequestMethod == 'POST') {
let prepare = function (query, settings) {
initialQuery[searchKey] = query;
settings.type = "POST";
settings.contentType = "application/json; charset=UTF-8";
settings.data = JSON.stringify(initialQuery);
return settings;
}
bloodhound.remote.prepare = prepare;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…