首页 > 解决方案 > 我如何使用 javascript fetch api 插入数据

问题描述

我正在尝试获取数据以形成我的view page使用fetch

结果:

var_dump($_POST)然后结果显示array(0) {}平均空数组

 function newCustomerAdd(){
  url = "data.php";
  const x = {
      name : "hasan",
      roll : 1
  }
 fetch(url,{
     method : "POST",
     body : JSON.stringify(x),
     headers: { 
        'Accept': 'application/json',
        'Content-Type': 'application/json'
     },
 }).then(function(response){
     return response.text();
 }).then(function(text){
    console.log(text);
 }).catch(function(error){
    console.log(error);
 })

 }

但是var_dump($_POST)结果显示array(0) {}平均空数组

我的问题如何从我的view page

标签: javascriptphpjsoncodeigniter

解决方案


JavaScript Code

  function newCustomerAdd(){
  url = "data.php";
  let x = {
      name : "hasan",
      roll : 1
  }
 fetch(url,{
     method : "POST",
     body : JSON.stringify(x),
     headers: { 
        'Content-Type': 'application/text'
     },
 }).then(function(response){
     return response.text();
 }).then(function(text){
    console.log(text);
 }).catch(function(error){
    console.log(error);
  })
 }

PHP code 只需获取数据

$content = json_decode(file_get_contents("php://input"));
print_r($content);

推荐阅读