我只是尝试使用API并在浏览器中显示结果。
为了测试,我安装了chrome扩展以绕过CORS问题,因此我“认为”这不是问题,但我甚至无法记录结果?不确定我错过了什么?
我在函数的回调函数中有一个console.log(data)来获取api,但是什么都没出现?
const NAMEURL = "https://uzby.com/api.php"
// get data from api
function getDataFromApi(value, callback){
const QUERY = {
min:`${value}`,
max:`${value}`
}
$.getJSON(NAMEURL, QUERY, callback)
}
function renderResult(result){
return `${result}`;
}
// render results to page
function displayName(data){
console.log(data);
const results = renderResult(data);
$('.nameResult').html(results);
}
// wait for user to submit
function watchSubmit() {
$('.js-search-form').submit(event => {
event.preventDefault();
const queryTarget = $(event.currentTarget).find('#js-dropValue');
const thisquery = queryTarget.val();
getDataFromApi(thisquery, displayName);
});
}
// running the watch submit function waiting for click
$(watchSubmit);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>title</title>
<link rel="stylesheet" href="style.css">
<link rel="shortcut icon" type="image/png" href="CW-favicon.png">
</head>
<body>
<div class="container">
<header>
<h1>Heading 1</h1>
</header>
<section role="main" id="main">
<div class="titlerow">
<h2>Tagline</h2>
</div>
<div class="buttonrow">
<form action="#" class="js-search-form">
<label for="js-dropValue">Number of Letters
<select name="js-dropValue" id="js-dropValue" >
<option value="choose">choose the number of letters</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</label>
<button type="submit">Create my name!</button>
</form>
</div>
<div class="nameResult">
</div>
</section>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="jquery-3.3.1.min.js"><\/script>')</script>
<script src="script.js"></script>
</body>
</html>
答案 0 :(得分:0)
@timHutchison给了我一个帮助我的重要提示。我最后只使用XMLHTTPRequest来完成数据的获取。