dshakcsq64956 2018-03-17 00:13
浏览 51
已采纳

通过POST将JSON字符串传递给PHP [关闭]

I have a page that is part of CRUD on which I can edit my data and send it to Update action of my php app. Basically, it is a HTML form with input fields. On this page I'm trying to implement some kind of drag-n-drop list arrangement via jQuery plugin. After sorting elements I create an array by js script that holds my hierarchy and it looks like this:

[
    {
        "id": 21,
        "name": "John"
    },
    [
        {
            "id": 25,
            "name": "Bill"
        },
        {
            "id": 20,
            "name": "Ann"
        }
    ],
    {
        "id": 18,
        "name": "Sally"
    },
    {
        "id": 24,
        "name": "Tom"
    }
]

Now, how can I pass this array from javascript to my update action via POST with the rest of my form so I can store it in DB in a proper JSON format?

  • 写回答

1条回答 默认 最新

  • dou4121 2018-03-17 00:34
    关注

    Option 1

    You can create a single JS object containing all your data (your form data and your hierarchical array). Afterwards, you can send that using jQuery .ajax() method or .post() method.

    Querying form inputs using jquery

    var formValues = {
        nameField1: $(field1Selector).val(),
        nameField2: $(field2Selector).val(),
        //(...) the remaining fields
    
        //variable holding your array
        arrangement: dragAndDropArray
     };
    

    Then, you can send that request to the server by

    $.ajax({
        url: actionUrl,
        method: 'POST',
        data: formValues //here you're setting the payload of your POST request
    });
    

    here's the documentation for the .ajax() method

    Option 2

    Another option is to create a hidden input field inside your form, and set its value to the JSON string of your JS array.

    Adding a hidden field to your form like

    <input type="hidden" id="hierarchical-array-input" name="hierarchivalArr" />
    

    Then, every time you update your array, you want to set the value of the hidden input like so:

    $('#hierarchical-array-input').val(JSON.stringify(hierarchicalArr));
    

    You need to handle the values in your PHP on both cases. I suggest you try it out and debug how the PHP is parsing the data.

    Note

    You can also use the first method with a plugin that queries the form and generates a JS object for you. Like,

    jquery form serialize JSON

    jquery input values

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?