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

FormData Passes Free Format Data to Backend T...
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) .then((response)=>{ return response.json(); }) .then((responseData)=>{ // Here we go on to explain }) .catch((error)=>{ console.error("An error occurred during the test"); console.log(error) })

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", type2:[ 1, 2, ] } // Simply put, all forms supported by json are possible // Save the results in FormData below formData.append('data',JSON.stringify(returnData));
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 $post_data=json_decode(htmlspecialchars_decode($_POST['data']),true);

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 $returnData=json_encode($post_data); // 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') .then((response)=>{ return response.json(); }) .then((responseData)=>{ // Here you can print the data console.log(responseData.returnData); }) .catch((error)=>{ console.error("Error parsing backend return data"); console.log(error); })

17 July 2020, 10:49 | Views: 4449

Add new comment

For adding a comment, please log in
or create account

0 comments