當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


p5.js httpPost()用法及代碼示例

p5.j​​s中的httpPost()函數用於執行HTTP POST請求。如果未指定,則p5將根據URL自動猜測返回的數據類型。

返回的數據可以加載到preload()函數中,以便可以在程序中立即對其進行訪問。

用法:



httpPost( path, [datatype], [data], [callback], [errorCallback] )

OR

httpPost( path, data, [callback], [errorCallback] )

OR

httpPost( path, callback, [errorCallback] )

參數:該函數接受上述和以下所述的五個參數:

  • path:它是一個字符串,表示要加載的URL或文件的路徑。
  • datatype:它是一個字符串,用於指定將要接收的數據類型。它可以具有“json”,“jsonp”,“xml”或“text”的值。如果未指定參數,則默認為‘text’。它是一個可選參數。
  • data:它是一個對象或布爾值,用於指定隨請求傳遞的參數數據。
  • callback:當該函數成功執行時,將調用該函數。該函數的第一個參數是從API返回的數據。它是一個可選參數。
  • errorCallback:如果執行該函數時有任何錯誤,則調用該函數。此函數的第一個參數是錯誤響應。它是一個可選參數。

返回值:它返回一個承諾,當操作成功完成時,可以用數據來解決該承諾,或者在發生錯誤時將其拒絕。

以下示例說明了p5.js中的httpPost()函數:

範例1:

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); 
  }); 
}

輸出:
post-request-btn

範例2:

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




相關用法


注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 p5.js | httpPost() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。