p5.js | httpPost()函数
p5.js 中的httpPost()函数用于执行 HTTP POST 请求。返回的数据类型由 p5 根据 URL 自动猜测,如果未指定。返回的数据可以在preload()函数中加载,以便可以在程序中立即访问。句法:
httpPost( path, [datatype], [data], [callback], [errorCallback] )
或者
httpPost( path, data, [callback], [errorCallback] )
或者
httpPost( path, callback, [errorCallback] )
参数:此函数接受上述五个参数,如下所述:
- path:它是一个字符串,表示要加载的 URL 或文件的路径。
- datatype:它是一个字符串,指定将接收的数据类型。它可以具有“json”、“jsonp”、“xml”或“text”的值。如果没有指定参数,它将默认为“文本”。它是一个可选参数。
- data:它是一个Object或一个布尔值,指定随请求传递的参数数据。
- callback:该函数执行成功时调用的函数。此函数的第一个参数是从 API 返回的数据。它是一个可选参数。
- errorCallback:这是一个函数,如果执行该函数有任何错误,则调用该函数。此函数的第一个参数是错误响应。它是一个可选参数。
返回值:它返回一个promise,可以在操作成功完成时用数据解决,或者在发生错误时被拒绝。
以下示例说明了 p5.js 中的httpPost()函数:
示例 1:
javascript
function setup() {
createCanvas(550, 200);
textSize(18);
text("Click on the button below"+
" to send a POST request.", 20, 40);
postBtn = createButton("Post Request");
postBtn.position(30, 60);
postBtn.mouseClicked(postRequest);
}
function postRequest() {
// Do a POST request to the test API
let api_url = 'https://reqres.in/api/users';
// Example POST data
let postData = { id: 1, name: "Sam",
email: "sam@samcorp.com" };
httpPost(api_url, 'json', postData, function (response) {
text("Data returned from API", 20, 100);
text("The ID in the data is: "
+ response.id, 20, 140);
text("The Name in the data is: "
+ response.name, 20, 160);
text("The Email in the data is: "
+ response.email, 20, 180);
});
}
javascript
function setup() {
createCanvas(550, 200);
textSize(18);
// Do a POST request to the test API
let api_url =
'https://reqres.in/api/users';
let postData = { id: 1, name: "James",
email: "james@james.j.com" };
httpPost(api_url, 'json', postData,
onSuccessfulFetch, onErrorFetch);
}
function onSuccessfulFetch(response) {
text("Data returned from API", 20, 60);
text("The ID in the data is: "
+ response.id, 20, 100);
text("The Name in the data is: "
+ response.name, 20, 120);
text("The Email in the data is: "
+ response.email, 20, 140);
}
function onErrorFetch() {
text("There was an error doing"+
" the request.", 20, 60);
}
输出:
示例 2:
javascript
function setup() {
createCanvas(550, 200);
textSize(18);
// Do a POST request to the test API
let api_url =
'https://reqres.in/api/users';
let postData = { id: 1, name: "James",
email: "james@james.j.com" };
httpPost(api_url, 'json', postData,
onSuccessfulFetch, onErrorFetch);
}
function onSuccessfulFetch(response) {
text("Data returned from API", 20, 60);
text("The ID in the data is: "
+ response.id, 20, 100);
text("The Name in the data is: "
+ response.name, 20, 120);
text("The Email in the data is: "
+ response.email, 20, 140);
}
function onErrorFetch() {
text("There was an error doing"+
" the request.", 20, 60);
}
输出:
在线编辑器: https://editor.p5js.org/
环境设置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
参考: https://p5js.org/reference/#/p5/httpPost