How to grab data using fetch() API POST method in PHP?

后端 未结 3 1520
野的像风
野的像风 2021-02-02 00:42

I am trying to use fetch() API POST method in order to grab the POST data in PHP.

Here is what I have tried:

var x = \"hello\";
fetch(url,{m         


        
3条回答
  •  太阳男子
    2021-02-02 01:05

    It depends:

    If you want to $_GET['x'], you need to send the data in the querystring:

    var url = '/your/url?x=hello';
    
    fetch(url)
    .then(function (response) {
      return response.text();
    })
    .then(function (body) {
      console.log(body);
    });
    

    If you want to $_POST['x'], you need to send the data as FormData:

    var url = '/your/url';
    var formData = new FormData();
    formData.append('x', 'hello');
    
    fetch(url, { method: 'POST', body: formData })
    .then(function (response) {
      return response.text();
    })
    .then(function (body) {
      console.log(body);
    });
    

提交回复
热议问题