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

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

报告相同问题?

悬赏问题

  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图