我正在尝试使用Unsplash API通过用户输入生成图像。到目前为止,当query =进行硬编码时,我已经能够检索图像,但是我希望结果根据用户键入并提交到查询的内容而有所不同。下面,我已将“狗”硬编码为查询输入。
到目前为止是我的代码:
var client_id = "fcbcd3e60e7f6615d0e5c64ab8e830d9695c4c30a74586e8d234f9835923ad75";
$("#fieldsubmit").click(function(){
query = $("#query").val();
})
$.getJSON('https://api.unsplash.com/search/photos?page=1&query=dog&client_id=fcbcd3e60e7f6615d0e5c64ab8e830d9695c4c30a74586e8d234f9835923ad75', function(data) {
console.log(data);
var imageList = data.results;
$.each(imageList, function(i, val) {
var image = val;
var imageURL = val.urls.regular;
var imageWidth = val.width;
console.log(imageURL);
$('.grid').append('<div class="image"><img src="'+ imageURL +'"</div>')
});
});
要么将JSON调用放入要在点击处理程序的回调函数中调用的函数中,要么将其添加到回调函数本身中(就像我在下面所做的那样,然后使用template literal将变量直接嵌入到字符串。
$("#fieldsubmit").click(function(){
const query = $("#query").val();
const endpoint = 'https://api.unsplash.com/search/photos';
const page = 1;
$.getJSON(`${endpoint}?page=${page}&query=${query}&client_id=${client_id}`, function(data) {
// ...
});
});