p5.js中的httpGet()函數用於執行HTTP GET請求。如果未指定,則p5將根據URL自動猜測返回的數據類型。
可以將數據加載到preload()函數中,以便可以在程序中立即對其進行訪問。
用法:
httpGet( path, [datatype], [data], [callback], [errorCallback] )
OR
httpGet( path, data, [callback], [errorCallback] )
OR
httpGet( path, callback, [errorCallback] )
參數:該函數接受上述和以下所述的五個參數。
- path:它是一個字符串,表示要加載的URL或文件的路徑。
- datatype:它是一個字符串,用於指定將要接收的數據類型。它可以具有“json”,“jsonp”,“binary”,“arrayBuffer”,“xml”或“text”的值。使用‘binary’數據類型將返回Blob對象,而使用“ arrayBuffer”將返回類型化數組。如果未指定參數,則默認為‘text’。它是一個可選參數。
- data:它是一個對象或布爾值,用於指定隨請求傳遞的參數數據。
- callback:當該函數成功執行時,將調用該函數。該函數的第一個參數是從API返回的數據。它是一個可選參數。
- errorCallback:如果執行該函數時有任何錯誤,則調用該函數。此函數的第一個參數是錯誤響應。它是一個可選參數。
返回值:它返回一個承諾,當操作成功完成時,可以用數據來解決該承諾,或者在發生錯誤時將其拒絕。
以下示例說明了p5.js中的httpGet()函數:
範例1:
let user_data;
function preload() {
// Get a random user from the test API
let api_url =
'https://reqres.in/api/users/' + int(random(1, 10));
httpGet(api_url, 'json', false, function (response) {
user_data = response;
});
// Log the recieved data to console
console.log(user_data);
}
function setup() {
createCanvas(550, 200);
textSize(18);
}
function draw() {
clear();
if (!user_data)
return;
text("Data fetched from API, can be viewed "
+ "in console", 20, 60);
text("The First Name in the data is:"
+ user_data.data.first_name, 20, 100);
text("The Last Name in the data is:"
+ user_data.data.last_name, 20, 120);
text("The Email in the data is:"
+ user_data.data.email, 20, 140);
}
輸出:
範例2:
function setup() {
createCanvas(550, 200);
textSize(18);
// Get a random user from the test API
let api_url =
'https://reqres.in/api/users/' + int(random(1, 10));
httpGet(api_url, 'json', false, onSuccessfulFetch, onErrorFetch);
}
function onSuccessfulFetch(response) {
text("Data successfully fetched from API, "
+ "can be viewed in console", 20, 60);
text("The First Name in the data is:"
+ response.data.first_name, 20, 100);
text("The Last Name in the data is:"
+ response.data.last_name, 20, 120);
text("The Email in the data is:"
+ response.data.email, 20, 140);
}
function onErrorFetch() {
text("There was an error fetching the data.", 20, 60);
}
輸出:
在線編輯: https://editor.p5js.org/
環境設置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
參考: https://p5js.org/reference/#/p5/httpGet
相關用法
- d3.js d3.hsl()用法及代碼示例
- d3.js d3.map.set()用法及代碼示例
- d3.js d3.min()用法及代碼示例
- p5.js pan()用法及代碼示例
- PHP ord()用法及代碼示例
- PHP each()用法及代碼示例
- p5.js hue()用法及代碼示例
- p5.js min()用法及代碼示例
- p5.js max()用法及代碼示例
- p5.js cos()用法及代碼示例
- p5.js log()用法及代碼示例
注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 p5.js | httpGet() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。