bouquins-bchs/search.js
2017-01-14 18:48:08 +01:00

104 lines
2.7 KiB
JavaScript

var app = new Vue({
el: '#app',
data: {
urlParams: {},
authors: [],
books: [],
series: [],
booksCount: 0
},
methods: {
urlParse: function() {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
this.urlParams[decode(match[1])] = decode(match[2]);
},
sendQuery: function(url, error, success) {
var xmh = new XMLHttpRequest();
var v;
xmh.onreadystatechange = function() {
v = xmh.responseText;
if (xmh.readyState === 4 && xmh.status === 200) {
var res;
try {
res = JSON.parse(v);
} catch (err) {
if (null !== error)
error(err.name, err.message);
}
if (null !== success)
success(res);
} else if (xmh.readyState === 4) {
if (null !== error)
error(xmh.status, v);
}
};
xmh.open('GET', url, true);
xmh.send(null);
},
stdError: function(code, resp) {
console.log('ERROR ' + code + ': ' + resp);
},
searchParams: function(url) {
var res = url;
var first = true;
for (var i=0; i<this.terms.length; i++) {
var t = this.terms[i];
if (t.trim()) {
if (first) {
first = false;
res += '?';
} else
res += '&';
res += 'term=' + encodeURIComponent(t.trim());
}
}
return res;
},
searchBooksSuccess: function(res) {
this.booksCount = res.count;
this.books = res.books;
},
searchBooks: function() {
this.sendQuery(this.searchParams('cgi-bin/bouquins/books'), this.stdError, this.searchBooksSuccess);
},
searchAll: function() {
this.clear();
this.searchBooks();
},
clear: function() {
this.authors = [];
this.books = [];
this.series = [];
this.booksCount = 0;
},
searchFull: function() {
if (document.getElementById("q").value) {
this.clear();
this.terms = document.getElementById("q").value.split(' ');
// TODO criteria
this.searchBooks();
}
},
searchUrl: function() {
if (this.urlParams.q) {
this.terms = this.urlParams.q.split(' ');
this.searchAll();
document.getElementById("q").value = this.urlParams.q;
}
}
},
created: function() {
this.urlParse();
},
mounted: function() {
this.searchUrl();
}
})