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

通过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?

我有一个页面是CRUD的一部分,我可以在其上编辑我的数据并将其发送到我的更新操作 PHP应用程序。 基本上,它是一个带有输入字段的HTML表单。 在这个页面上我试图通过jQuery插件实现某种拖放列表排列。 排序元素后,我通过js脚本创建一个数组来保存我的层次结构,它看起来像这样: p>

  [
 {
“id”:21,
“name  “:”John“
},
 [
 {
”id“:25,
”名称“:”Bill“
},
 {
”id“:20,
” 名称“:”Ann“
} 
 
],
 {
”id“:18,
”name“:”Sally“
},
 {
”id“:24,
  “name”:“Tom”
} 
] 
  code>  pre> 
 
 

现在,如何通过POST将此数组从javascript传递到我的更新操作,其余部分 我的表单,所以我可以以适当的JSON格式将其存储在数据库中? p> div>

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