jQuery的
$('#speichern').live('click',function () { // [a] var data_save = $('#form_rechn').serializeArray(); var data_save_ser = $('#form_rechn').serialize(); //[b] // [a] data_save[data_save.length] = {"name":"action","value":"save" },{"name":"total","value": Number($('#grandTotal').text().replace(/EUR/g,""))}; var addintional = 'action=save&MysqL=update' + '&' + 'total=' + Number($('#grandTotal').text().replace(/EUR/g,""));//[b] var data_save = data_save_ser + '&' + addintional;//[b] $.ajax({ type : "POST",cache : false,url : 'invoice_new_action.PHP',data : data_save,error:function (xhr,ajaxOptions,thrownError){ alert(xhr.status); alert(thrownError); },success : function(data) { $.fancybox(data); } }); });
[b]部分效果很好;但是,为什么[a] -part不起作用?这不推动:
,{“name”:“total”,“value”:[..]
并[b] -version
阵列([pnr_item_1] =→1 [pkt_item_1] => HostingXXL [desc_item_1] => 20GB,1x.de [qty_item_1] =→4 [price_item_1] => 15.5 … [动作] => ; save [MysqL] => update [total] => 62)
[厌恶
阵列([pnr_item_1] =→1 [pkt_item_1] => HostingXXL [desc_item_1] => 20GB,1x.de [qty_item_1] =→4 [price_item_1] => 15.5 … [动作] => ; 保存 )
解决方法
它应该如下所示:
$('#speichern').live('click',function () { var data_save = $('#form_rechn').serializeArray(); data_save.push({ name: "action",value: "save" }); data_save.push({ name: "MysqL",value: "update" }); data_save.push({ name: "total",value: Number($('#grandTotal').text().replace(/EUR/g,"")) }); $.ajax({ type : "POST",error : function (xhr,thrownError){ alert(xhr.status); alert(thrownError); },success : function(data) { $.fancybox(data); } }); });
你想要推送到数组的是{name:“name”,value:“value”}形式的对象,然后它们将被正确地序列化/编码.选项[a](它的校正形式)通常比选项[b]好得多,因为[b]不是属性编码的,并且当任何无效字符在那里滑动以弄乱变量时将失败.在这种情况下,因为你控制了附加的内容,所以你是安全的……但是最好是总是有效的路径:永远不要直接将数据参数创建为字符串.
至于为什么[a]不起作用:
data_save[data_save.length] = {"name":"action",""))};
这是无效的,你不能一次分配2件事,你需要这样做:
data_save[data_save.length] = {"name":"action","value":"save" }; data_save[data_save.length] = {"name":"total",""))};
或者这(我的首选方法,如上所用):
data_save.push({"name":"action","value":"save" }); data_save.push({"name":"total",""))});
….或者,使用$.merge()
(有点浪费,但看起来更干净),像这样:
$.merge(data_save,[{"name":"action",""))}]);