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 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?