将输入字段文本放入变量中并将其用于 jquery JSON get 请求

Putting input field text into variable and using that for jquery JSON get request

本文关键字:用于 jquery JSON 请求 get 字段 输入 文本 变量      更新时间:2023-09-26

嘿,所以我几乎是一个jquery/javascript菜鸟,我试图创建一个简单的搜索框,它从OMDB API返回电影数据。可悲的是,我认为它没有正确传递输入数据,所以我觉得在将输入文本传递到变量时我做错了什么,因为它没有传递我放入表单字段的任何内容。有谁知道我在这里出了什么问题?

这是我到目前为止的代码:

    function getSearchResult() {
      var search = document.getElementById("title").innerHTML;
      jQuery.getJSON("http://www.omdbapi.com/?t=" + search + "=json", function(result) {
        jQuery.each(result, function(i, field) {
          jQuery("div").append(field + " ");
        });
      });
    };
<form id="searchForm">
  Search for movie:
  <input type="text" name=movie_title id="title">
  <input type="button" value="Submit" onClick="getSearchResult()">
</form>

你在代码中犯了一些错误:

要获取输入的值,请使用:

var search = document.getElementById("title").value;

而不是内部HTML

然后,您用于调用 API 的 url 错误,请在使用之前查看文档:http://www.omdbapi.com/

使用此网址:

"http://www.omdbapi.com/?t=" + search + "&y=&plot=short&r=json"

完整代码

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.2.2.min.js"></script>
<script>
$(function() {
    $('#search').on('click', function() {
        var search = document.getElementById("title").value;
        $.getJSON(
            "http://www.omdbapi.com/?t=" + search + "&y=&plot=short&r=json",
            function(result) {
                $.each(result, function(i, field){
                    $("body").append(field + " ");
                });
            }
        );
    });
});
</script>
</head>
<body>
    Search for movie:<input type="text" name="movie_title" id="title" />
    <input type="button" id="search" value="Submit" />
</body>
</html>
你有一个奇怪的混合体,包括

vanilla JS和jQuery;考虑改变你的方法,以充分利用jQuery为你提供的工具。 请在下面找到可能有助于指向该方向的代码(请注意对 HTML 的更新和 onClick 对按钮本身的附件):

.JS:

$('#searchForm input[type="button"]').on('click', function(){
    var search = $('#searchForm input').text();
    var searchResult = $('#searchResult'); //save reference to DOM object
    $.getJSON("https://www.omdbapi.com/?t=" + search + "=json", function(response){
        console.log(response);
        searchResult.empty();
        if(response.Response === 'False') {
            searchResult.append('<p>'+response.Error+'</p>');
        } else {
            $.each(result, function(i, field){
                searchResult.append('<p>'+field+'</p>');
            });
        }
    });
});

.HTML:

<form id="searchForm">
  Search for movie:<input type="text" name=movie_title id="title">
  <input type="button" value="Submit" >
</form>
<div id="searchResult"></div>

您可以在此处运行它(尽管我的快速搜索都没有返回结果,因此我无法验证成功条件):https://jsfiddle.net/wct58tco/