当我使用ajax将串行数据发送到PHP文件时,有时会根据我的操作方式对其进行URL编码。
最初我有以下代码,运行良好:
$.ajax({
type: 'POST',
url: 'ajax-process.php',
data: $("#sitestructure-form").serialize(),
success: function(d){$("#structureupdate").html(d);}
});
数据被发送到我的PHP文件中,我可以回显它,它看起来是这样的。
[{"id":20,"children":[{"id":21}]},{"id":19},{"id":18,"children":[{"id":14}]},{"id":16},{"id":13,"children":[{"id":11}]},{"id":17},{"id":15},{"id":12}]
我想发送多个数据,我将序列化的数据称为"order",并添加了"process",因此我将代码更新为以下内容:
$.ajax({
type: 'POST',
url: 'ajax-process.php',
data: {
order: $("#sitestructure-form").serialize(),
process: "sitemap-reordernavigation"
},
success: function(d){$("#structureupdate").html(d);}
});
然而,当我检索按"顺序"发送的串行数据时,输出看起来像这样:
data=%5B%7B%22id%22%3A20%2C%22children%22%3A%5B%7B%22id%22%3A21%7D%5D%7D%2C%7B%22id%22%3A19%7D%2C%7B%22id%22%3A18%2C%22children%22%3A%5B%7B%22id%22%3A14%7D%5D%7D%2C%7B%22id%22%3A16%7D%2C%7B%22id%22%3A13%2C%22children%22%3A%5B%7B%22id%22%3A11%7D%5D%7D%2C%7B%22id%22%3A17%7D%2C%7B%22id%22%3A15%7D%2C%7B%22id%22%3A12%7D%5D
我能想到的解决这个问题的唯一方法是使用php对其进行url解码,然后使用str_replace删除前面的"data="位,就像这样
$data = str_replace("data=","",urldecode($_POST['order']));
我如何才能让它与AJAX一起工作,这样我就不必对它进行URL解码了?
我试过使用一个变量并将processData设置为false,但这似乎不起作用。
var order = $("#sitestructure-form").serialize();
$.ajax({
type: 'POST',
url: 'ajax-process.php',
processData: false,
data: {
order: order,
process: "sitemap-reordernavigation"
},
success: function(d){$("#structureupdate").html(d);}
});
我对AJAX/Jquery的了解非常有限,所以如果有任何帮助,我们将不胜感激。
这是因为您第一次向数据属性提供序列化的文本字符串,而jQuery不会将其转换为序列化的字符串。第二步,您将一个对象分配给具有序列化文本字符串的"order"属性的数据属性,因此jQuery基本上对其进行了双重编码。为了使其发挥您想要的作用,您必须将表单转换为一个对象,并将您的"order"属性分配给该对象。请参阅本文:使用jQuery 将表单数据转换为JavaScript对象
// taking the example from the above link, you do this instead
order = $("#sitestructure-form"). serializeObject();
通过以下操作修复:
$.ajax({
type: 'POST',
url: 'ajax-process.php?',
data: $("#sitestructure-form").serialize() + "&action=sitemap-reordernavigation",
success: function(d){$("#structureupdate").html(d);}
});