JQuery parameter serialization without the bracket mess

后端 未结 2 1641
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 07:31

I\'m using JQuery to make a JSON request back to the server and it seems that it\'s parameter serialization is hard-coded to what PHP expects instead of being generic in nat

2条回答
  •  醉话见心
    2020-12-05 07:58

    The object can be converted to a parametrized string using $.param(obj,true). The second boolean parameter indicates the traditional method of serializing an object should be used. The traditional method does not use square brackets when it encounters the same parameter name. The serialized string returned from $.param can be passed via any ajax method.

    This method is preferred over using $.ajaxSetup() as noted by the jQuery Documentation that states:

    Note: The settings specified here will affect all calls to $.ajax or AJAX-based derivatives such as $.get(). This can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings. For that reason we strongly recommend against using this API. Instead, set the options explicitly in the call or define a simple plugin to do so.

    Example:

    var obj = {myProp: "test", arr: [1,2,3,4]};
    var serializedObj = $.param(obj, true); //myprop=test&arr=1&arr=2&arr=3&arr=4
    
    $.post(url,serializedObj,function(){});
    

提交回复
热议问题