fetch pass-by instance code (back-end PHP)

FormData Passes Free Format Data to Backend

The first is the js code:

let formData=new FormData();
let headres = {
            method: 'post',
            credentials: 'include',
            headers: {},
            body: formData
        fetch("The address of your backend",headres)
                return response.json();
                // Here we go on to explain
                console.error("An error occurred during the test");

The next question is how to insert data flexibly in FormData and pass it to back-end parsing.The best way to do this is to convert the passed value into a string:

let returnData={
    type1:"Directly like this json format",
        {type3:"This form of freedom is also possible"}
// Simply put, all forms supported by json are possible
// Save the results in FormData below

Backend parse code

This shows back-end parsing, which uses PHP.But the ideas should be consistent:

// Backend processing relies on two functions
// htmlspecialchars_decode removes extra quotation marks and character translation
// json_decode parsing json

After processing by the above two functions, the json in the formData above will be parsed into an array, where the array is still an array.

Front end parses its own passed value

The last one that needs to be handled by the back-end is to pass the value from the front-end back to the front-end parsing:

// Backend is required to convert the value to json for front-end parsing
// Pass the value back to the front end
echo json_encode(array('returnData'=>$returnData));

After the front-end to parse, the basic is the general fetch routine

fetch('Get the route of the returned data above')
        return response.json();
        // Here you can print the data
        console.error("Error parsing backend return data");


Posted on Fri, 17 Jul 2020 10:50:43 -0400 by tacojohn