帮我写一个对接chatgpt api的页面
很高兴为您提供帮助。在对接ChatGPT API之前,您需要先获取API密钥。如果您还没有API密钥,请先注册并创建一个ChatGPT账户。
接下来,我们将为您提供一个简单的HTML页面,该页面可以向ChatGPT API发送请求并接收响应。请按照以下步骤操作:
- 在您的项目文件夹中创建一个名为“index.html”的新文件,并将以下代码复制并粘贴到文件中。
<!DOCTYPE html>
<html>
<head>
<title>ChatGPT API Demo</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>ChatGPT API Demo</h1>
<div>
<label for="input">Input:</label>
<input type="text" id="input" name="input">
</div>
<button id="submit">Submit</button>
<div id="output"></div>
<script>
$(document).ready(function() {
$("#submit").click(function() {
var input = $("#input").val();
$.ajax({
type: "POST",
url: "https://api.chatgpt.com/v1/chat",
headers: {
"Authorization": "Bearer YOUR_API_KEY_HERE",
"Content-Type": "application/json"
},
data: JSON.stringify({
"message": input,
"context": null
}),
dataType: "json",
success: function(response) {
$("#output").html(response.response);
},
error: function(xhr, status, error) {
console.log(xhr);
$("#output").html("Error: " + xhr.responseJSON.message);
}
});
});
});
</script>
</body>
</html>
-
在代码中,将“YOUR_API_KEY_HERE”替换为您的API密钥。
-
保存并打开“index.html”文件,您将看到一个简单的页面,其中包含一个文本框和一个“提交”按钮。
-
输入您想要发送给ChatGPT API的消息,并单击“提交”按钮。
-
等待API响应并在页面下方的“Output”部分查看响应。
这就是一个简单的对接ChatGPT API的页面。您可以根据需要进行修改和自定义。
原文地址: https://www.cveoy.top/t/topic/EW4 著作权归作者所有。请勿转载和采集!