首页 > 解决方案 > NULL 数据对象显示在我的 php 脚本中

问题描述

我想在FETCH api的帮助下将数据 ( 'ABCDEF','23','1234567890','abc@def.com' and the image 'profile.jpg') 发送到我的脚本中。php

我的 HTML:

<form id="details" class="form">

    Full name: <strong name="name_1">ABCDEF</strong><br><br>
    ID No:<strong name="org_number_1">23</strong><br><br>
    Mobile No:<strong name="ph_number_1">1234567890</strong><br><br>

    E-mail: <strong name="email_1">abc@def.com</strong><br><br>
    ID Card: <img src="profile.jpg" alt="preview" name="image" style="width: 100px; height: 100px;"><br><br>

    <button id="go" onclick="submit()"type="button" value="submit">Submit</button>

</form>

我的JavaScript:

function submit(){

    var nme=document.getElementsByName("name_1")[0].innerHTML;
    var id=document.getElementsByName("org_number_1")[0].innerHTML;
    var phone=document.getElementsByName("ph_number_1")[0].innerHTML;
    var email=document.getElementsByName("email_1")[0].innerHTML;
    var img=document.getElementsByName("image")[0].src;
    var dataString = {"name": nme, "email": email, "ID No": id, "Contact no": phone, "image": img};
    
    const dForm = document.getElementById('details');          
    dForm.addEventListener('submit', function(e) {
        e.preventDefault();
        fetch("database_registration.php",{
            method: 'post',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(dataString), 
        }).then(function (response){
            return response.text();
        }).then(function (text){
            console.log(text);
        }).catch(function (error){
            console.error(error);
        })
    });
 
}

我的PHP:

<?php
      $post_data = file_get_contents("php://input");
      $data = json_decode($post_data); 
      var_dump($data);         //shows NULL
?>

为什么是我的$data对象NULL?我如何获取这些数据?

编辑:我也跟着一步

标签: javascriptphphtmlfetchfile-get-contents

解决方案


为什么不逐一获取您的帖子输入并将它们分别定义在一个变量中?

$name = $_POST['name']
$id = $_POST['ID No']
$email = $_POST['email']
$phone = $_POST['ContactNo']
$img = $_POST['image']

推荐阅读