【问题标题】:convert normal submit form to ajax real time将普通提交表单实时转换为ajax
【发布时间】:2020-11-10 17:38:22
【问题描述】:

我是新来的,如果我的问题看起来很愚蠢,请原谅我

我有以下代码来搜索带有提交按钮(普通形式)的 youtube 视频

我想转为实时输入一旦用户写了任何单词,将获取结果取决于他写的内容

所以我补充

    $(".search_input").keyup(function(e) {

而不是

    $("form").on("submit", function(e) {

完整代码在这里https://jsfiddle.net/5ymndbax/

function tplawesome(e,t){res=e;for(var n=0;n<t.length;n++){res=res.replace(/\{\{(.*?)\}\}/g,function(e,r){return t[n][r]})}return res}

$(function() {
    $(".search_input").keyup(function(e) {
       e.preventDefault();
       // prepare the request
       var request = gapi.client.youtube.search.list({
            part: "snippet",
            type: "video",
            q: $("#search").val(),
            order: "viewCount",
            publishedAfter: "2000-01-01T00:00:00Z"
       }); 
       // execute the request
       request.execute(function(response) {
          var results = response.result;
          $("#results").html("");
          $.each(results.items, function(index, item) {
            $.get("tpl/item.html", function(data) {
                $("#results").append(tplawesome(data, [{"title":item.snippet.title, "videoid":item.id.videoId}]));
            });
          });
          resetVideoHeight();
       });
        
    });
    
    $(window).on("resize", resetVideoHeight);
});

function resetVideoHeight() {
    $(".video").css("height", $("#results").width() * 9/16);
}

function init() {
    gapi.client.setApiKey("key");
    gapi.client.load("youtube", "v3", function() {
        // yt api is ready
    });
}

我希望我能得到你的帮助❤ 对你们每个人都充满爱。

【问题讨论】:

    标签: javascript ajax youtube-api real-time youtube-data-api


    【解决方案1】:

    目前您正在使用 keyup,它将按字母检查条目。

    因此,您需要检查是否以“”,“,”结尾的键。等等,因为这主要意味着单词的结尾。

    现在,当我们有了单词时,我们想将它添加到 以前输入的单词,所以你需要 将 new_word 连接或附加到 previous_words。

    只有这样你才应该调用 AJAX 调用到使用 YouTube API 进行搜索的 URL 或脚本......

    应该是这样的:

    **

    event.preventDefault();
    $.ajax({
      type:"GET",
      url: "youtube url or some script preforming to yt api call",
      data:{"search": previous_words,},
      success:function(data){
        //display data somewhere
        console.log(data);
      }
    });

    【讨论】:

    • 感谢您的回复我有以下代码jsfiddle.net/5ymndbax 你能检查一下大多数添加apis.google.com/js/client.js 而不是ajax 中的URL 吗?
    • 你可以使用 url: "script.php "。大多数情况下我调用 php 脚本,但我猜你也可以调用 JS。您需要在调用脚本中准备好函数调用,以便它们执行。更好的是在脚本中使用 ajax 来处理调用 api 的函数中的请求。
    • 你可以使用 url:someFunction() 来调用 js 函数,只需取消引用即可。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 2020-06-07
    • 2012-08-16
    • 2012-03-18
    相关资源
    最近更新 更多