POST Request with Fetch API?

后端 未结 5 1725
鱼传尺愫
鱼传尺愫 2020-12-01 03:10

I know that with the new Fetch API (used here with ES2017\'s async/await) you can make a GET request like this:

async getData() {
          


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-01 03:15

    Here is a complete example: After spending hours tinkering with incomplete code snippets I finally managed to post some json from javascript, pick it up using php on a server, added a data field and finally updated the original web page. Here is the HTML, the PHP and the JS. My thanks to everyone who posted the original code fragments collected here. Similar code is on-line here: https://www.nbest.co.uk/Fetch/index.php

    
    
    
    
      
      
      Javascript Fetch Example
    
    
    
    

    Javascript Fetch Example

    Save this to index.php and view this page in your browser.

    This is the JSON before the fetch.

    This is the JSON after the fetch.

    // Save this as fetch.js -------------------------------------------------------------------------- function success(json) { document.getElementById('after').innerHTML = "AFTER: " + JSON.stringify(json); console.log("AFTER: " + JSON.stringify(json)); } // ---------------------------------------------------------------------------------------------- function failure(error) { document.getElementById('after').innerHTML = "ERROR: " + error; console.log("ERROR: " + error); } // ---------------------------------------------------------------------------------------------- function myButtonClick() { var url = 'json.php'; var before = {foo: 'Hello World!'}; document.getElementById('before').innerHTML = "BEFORE: " + JSON.stringify(before); console.log("BEFORE: " + JSON.stringify(before)); fetch(url, { method: 'POST', body: JSON.stringify(before), headers:{ 'Content-Type': 'application/json' } }).then(res => res.json()) .then(response => success(response)) .catch(error => failure(error)); } // ----------------------------------------------------------------------------------------------

提交回复
热议问题