doudun3910 2014-01-02 19:53
浏览 17
已采纳

JSON或JS对象通过AJAX POST传递给PHP的最有效方式

On the face, it may appear that this is a repeat question. Please note that I have read through all the related posts and did not find any definite answer and/or the issue here is very different. Even some direction to some post or material clarifying the issues with specificity would be helpful. I am not looking for spoon feeding.

Here is the issue:

I have a form and I have some other meta-data (for lack of a better term) to be sent to the server which consists of configuration parameters. These are required along with the form data to be processed by a PhP back-end and return some complex JS and HTML markup.

Admittedly I am not a regular user of JSON but my reading pointed to using JSON for the non-form data and have the form data serialized separately and assign it to another property, as in:

var ser_data = $(form_selector).serialize();

var meta_data = { //Just for example
    name: 'John Doe',
    age:    62,
    address: '22 Park Avenue'
};

And then pass the data in .ajax as:

data_sent = data_sent = {'meta_data':meta_data, 'form_data':ser_data};

some_promise = $.ajax({
       url : '../php/json_test.php', 
       dataType: 'json',
       type : 'POST',
       cache    : false,
       data : data_sent
});

On the PhP side, I have to navigate $_POST[] at multiple levels to get to the data. Also, the form data loses the implicit URL decoding.

Of course, one way could be to manually construct the serialized string to be appended to the form serialized string as in

form_data_serialized...&name='John doe'&age=62... 

Am I on the wrong track all together? Is there an approach that is better and simpler? THANKS!

  • 写回答

2条回答 默认 最新

  • du6jws6975 2014-01-02 20:03
    关注

    .serialize simply creates a param string, for example, foo=bar&foobar=2. with this in mind, adding your additional params is basic string concatenation.

    var data_sent = $.param(meta_data) + "&" + ser_data;
    

    Convert meta_data into a param string, then append your serialized form data to it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题