我有一个可以使用的 jquery 自动完成菜单。它显示包含作者、标题和书籍图像的书籍列表。我想添加点击书籍图片并发布书名的功能来表达app.post以显示书籍简介页面。
这是 jquery 自动完成代码。我添加了不起作用的选择事件。
<script type="text/javascript">
$(document).ready(function() {
$("#findBook").autocomplete({
source: function (request, response) {
$.ajax({
method: "GET",
dataType: "json",
url: "https://www.googleapis.com/books/v1/volumes?q=" + request.term,
success: function (data) {
var transformed = data.items.map(function (book) {
return {
title: book.volumeInfo.title,
author: book.volumeInfo.author,
image: book.volumeInfo.imageLinks.thumbnail
};
});
response(transformed);
}
});
},
select: function(event, ui){
console.log(ui.title);
var id = ui.item.title;
$.ajax({
url: "/book_profile_b/" + id,
type: "POST",
dataType: 'html',
data: { id: id },
success: function(data){
alert(data);
var win = window.open();
win.document.write(data);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.responseText+" - "+thrownError)
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
},
}).autocomplete("instance")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + "<img src=\"" + item.image + "\" style=\"height: 40%;\" /><br />" + (item.author && item.author.length ? item.author.map(function (x) {
return x;
}).join(" | ") : '') + " - " + item.title + "</a>")
.appendTo(ul);
};
});
在 express 方面。这是我尝试将书名数据发送到的函数。
app.post('/book_profile_b/:encoded_id', function(req, response,err){
var book_title = req.params.encoded_id;
if(err){
console.log(err);
}
request("https://www.googleapis.com/books/v1/volumes?q=" + book_title,
function (error, resp, data) {
if (error) {
console.log(error);
}
else {
var gb_data = JSON.parse(data);
console.log(gb_data);
const gb_description = gb_data.items[0].volumeInfo.description;
const gb_image = gb_data.items[0].volumeInfo.imageLinks.thumbnail;
response.render('book_profile', {book_description: gb_description, book_image: gb_image});
}
});
});
最佳答案
$.post("/book_profile_b/" + id).done(function(data){
alert(data);
var win = window.open();
win.document.write(data);
}).
error(function (xhr, ajaxOptions, thrownError) {
console.log(xhr.responseText+" - "+thrownError)
alert("ERROR:" + xhr.responseText+" - "+thrownError);
});
你可以使用上面的代码块进行post调用吗?我已经删除了 dataType 并删除了不需要的数据,因为您已经在 url 中传递了 id。
我建议使用$.post
如果出现错误,也请分享该错误。
关于javascript - jQuery 自动完成菜单单击图像将数据发布到 Express 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60198500/