我试图使用ajax调用API。
api是https://rapidapi.com/brianiswu/api/genius?endpoint=apiendpoint_d2f41ea4-7d5c-4b2d-826a-807bffa7e78f

我无法使其正常工作。我在互联网上进行了搜索,但找不到或了解解决我的问题的方法。可能很简单,但请帮助我
这是我的代码:



<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
    <title>MusicApp</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>

</head>

<body>
	<form>
		<input type="text" id="inputText">
		<input type="submit" name="submit" id="submitBtn">
	</form>

	<div id="text"></div>
</body>

<script>

	$(document).ready(function(){
		var api="1f57380a81msh394cf453f4d1e73p1a0276jsnab0cd43f0df7";

		$('#submit').click(function(){
			artist=$('#inputText').val();

			$.ajax({
				method:"GET",
				url: "https://genius.p.rapidapi.com/search?q=" + artist + "&appid=" + api,
				success:function(resp){
					alert("successfully");
				},
				error:function(){
					alert("Something went TEREBLY WRONG!!!! \nYOU BROKE IT!");
				}
			})
		})
	})
</script>
</html>

最佳答案

将您的代码更改为以下代码:

$(document).ready(function(){
    var api="1f57380a81msh394cf453f4d1e73p1a0276jsnab0cd43f0df7";

    $('#submitBtn').click(function(){
        artist=$('#inputText').val();

        $.ajax({
            method:"GET",
            url: "https://genius.p.rapidapi.com/search?q=" + artist + "&appid=" + api,
            success:function(resp){
                alert("successfully");
            },
            error:function(){
                alert("Something went TEREBLY WRONG!!!! \nYOU BROKE IT!");
            }
        });
        return false;
    });
});

关于javascript - 如何使用AJAX从API调用和返回数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58936914/

10-11 12:51