Normal form submission vs. JSON

后端 未结 5 1992
生来不讨喜
生来不讨喜 2021-02-05 04:09

I see advantages of getting JSON response and formatting in client side but are there any advantages by using JSON for form submission compared to normal submission?

5条回答
  •  一向
    一向 (楼主)
    2021-02-05 04:45

    I don't see any apparent advantages for basic form submission. But when it comes to handling complex structures you'll start to realize the advantage of organizing your data.

    So if you have a simple contact form (name, email, message) stick with normal form POSTing. But think about submitting a complete user's CV for example, it's very annoying to handle the massive amount of variables in your server-side script.

    Here's an example for using JSON with PHP

    //Here are the submission data
    {
        "personalInformation": {
            "name": "hey",
            "age": "20"
        },
        "education": {
            "entry1": {
                "type": "Collage",
                "year": "2012"
            },
            "entry2": {
                "type": "Highschool",
                "year": "2010"
            }
        }
    }
    
    $CV_Data = json_decode($_POST['json_form'], true);
    $CV_Data['personalInformation']['name'];
    $CV_Data['personalInformation']['age'];
    //Or you can loop
    foreach($CV_Data['education'] as $entry){
       $entry['type'];
       $entry['year'];
    }
    

    As you can see, using JSON here makes it a lot easier for you to work on your data.

提交回复
热议问题