我正在尝试使用OMDb API。我正在设法寻找一部电影,但没有空间。只要我在搜索中使用空格,它就会返回null。
示例:
搜索:热门回复:{movieName:“Hot Fuzz”}
搜索:模糊返回:{movieName:“Fuzz”}
搜索:Hot Fuzz Return:{movieName:“No results”}
搜索:诗人的回归:{movieName:“Poet's Pub”}
搜索:Poet's Pu返回:{movieName:“没有结果”}
我假设作为特殊字符的空格格式不正确,因此会出现默认的返回字符串。我无法弄清楚如何解决它。有谁能指出我正确的方向?
HTML / JS:
<form id="fetchFilm" method="post">
<input id="searchString" type="text" name="searchString">
</form>
<br>
<p id="mTitle"></p>
<script>
$(function() {
$('form').each(function(e) {
$(this).find('input').keypress(function(e) {
// Enter pressed?
if(e.which == 10 || e.which == 13) {
e.preventDefault();
findFilm();
}
});
});
});
function findFilm() {
$.ajax({
url: "movieFinder.php",
type: "post",
dataType: 'json',
data: $('#searchString'), //Here is where I presume the problem may be.
success: function(data){
var movieTitle = data.movieName;
document.getElementById("mTitle").innerHTML = movieTitle;
},
});
}
</script>
PHP:
<?php
if(isset($_POST)) {
function curl_get_contents($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$searchString = $_POST['searchString'];
$url = "https://www.omdbapi.com/?apikey=MyKey&t=".$searchString;
$movie_json = json_decode(curl_get_contents($url), true);
$movie['movieName'] = $movie_json['Title'];
if(!empty($movie['movieName'])) {
//Do nothing
} else {
$movie['movieName'] = "No results";
}
echo
json_encode(array(
'movieName' => $movie['movieName']
))
;
}
?>
答案 0 :(得分:1)
$('#searchString')
为您提供jquery-wrapped元素,而不是输入值。试试这个:
data: $('#searchString').val()
答案 1 :(得分:1)
根据您获得的结果,在将搜索字符串应用为查询参数时,请尝试对搜索字符串进行URL编码:
这将有效: https://www.omdbapi.com/?apikey=&amp; T公司=热%20Fuzz