如何由用户更改js-src's正在打字

How to change js src by user's typing

本文关键字:用户 js-src      更新时间:2023-09-26

我使用Google Books API PHP,希望在用户键入搜索关键字时更改该关键字,以便立即返回标题提示。如何实现q=what user types right now

<script src="https://www.googleapis.com/books/v1/volumes?q=harry+potter&callback=handleResponse"></script>

要有效地做到这一点,请删除&callback=handleResponse,这样您得到的实际响应就是JSON。

在javascript中,将变量设置为:

var request = 'https://www.googleapis.com/books/v1/volumes';

有一个表单(包含文本区域和提交(处理程序,它有这样的东西:

$('#form').onsubmit(function(e){
  e.preventDefault();
  var keywords = $('#myTextAreaInputInsideTheForm').val();
  $.getJSON(request + '?q=' + keywords, function(data){
     //do stuff with the json response
     console.log(data);
  });
});

或者,如果您需要在每次文本区域中发生更改时调用XMLHTTPrequest

$('#myTextArea').on('keyup', function(){
      var keywords = $(this).val();
      $.getJSON(request + '?q=' + keywords, function(data){
         //do stuff with the json response
         console.log(data);
      });
});

编辑:我假设您使用的是文本区域,但<input type="text"/>也可以。

EDIT2:演示演示可能不起作用,因为谷歌现在返回403禁止。您不能多次调用URL,否则谷歌将阻止您的请求。我建议每写几封信就给它打电话。祝你好运

var request = 'https://www.googleapis.com/books/v1/volumes';
$('#myTextArea').on('keyup', function(){
      var keywords = $(this).val();
    if(keywords.length > 0 && keywords.length % 5 == 0){
          $.getJSON(request + '?q=' + keywords, function(data){
             //do stuff with the json response
             console.log(data);
          });
    }
});

使用keyup总比改变好。