2015-11-21 22 views
1

我试图创建一个URL,将输入文本传递给AJAX调用的查询字符串。在控制台中,我可以看到我将输入的文本捕获为一个字符串,但它不会传递到URL中,而是返回一个空对象。从文本输入创建动态URL =在URL中返回“undefinied”字符串

<form action="" method="GET"> 
    <input type="text" id="movie-title" placeholder="Enter a movie title"> 
    <input type="submit" id="sbmt-movie"> 

</form> 

$("#sbmt-movie").click(function(){ 
    var movie = $("#movie-title").val().toLowerCase(); 
    console.log("the movie title is " + movie); 
    var url = "https://api.themoviedb.org/3/search/movie?query=" + encodeURIComponent(url) + "&api_key=9b97ec8f92587c3e9a6a21e280bceba5"; 

$.ajax ({ 
    url: url, 
     dataType: "json", 
     success: function (data) { 
     console.log(data); 

     var list = data.list; 
     } 
}); //close .ajax  

});

这是我看到控制台的信息:

XHR加载完成:GET “https://api.themoviedb.org/3/search/movie?query=undefined&api_key=9b97ec8f92587c3e9a6a21e280bceba5”。

对象{页面:1,结果:数组[0],共TOTAL_RESULTS:0,TOTAL_PAGES:1}

Link to Codepen

回答

1

您的问题所在在该行

var url = "https://api.themoviedb.org/3/search/movie?query=" + encodeURIComponent(url) + "&api_key=9b97ec8f92587c3e9a6a21e280bceba5"; 

您正在尝试使用的功能encodeURIComponent()上技术上尚未定义的变量url。 我想你想要做的是encodeURIComponent(movie)

var url = "https://api.themoviedb.org/3/search/movie?query=" + encodeURIComponent(movie) + "&api_key=9b97ec8f92587c3e9a6a21e280bceba5"; 

看看我更新的codepen here

0

你传入url到encodeURIComponent方法,而不是movie