我正在使用jquery / JS和PHP进行简单的客户端/服务器通信。它工作正常,直到数据中包含'.'
。
尝试使用以下标题:
asdf-wq1 --> works
test1 --> works
bigip1.local --> '.' is replaced with '_'
我已将escape()
函数添加到我的代码中,但结果是一样的。
function xy(){
for (var i = 0; i < nodes.length; i++) {
var xy = escape(nodes[i].title) +"=" +escape(nodes[i].translate.x + "/" + nodes[i].translate.y);
$.ajax({
url: 'save_layout.php',
data: xy,
dataType: "text",
type: 'post',
success: function(output) {
$("#output").html(output);
},
error: function (response, status, error) {
alert("error" + response.responseText);
}
});
}
}
PHP:
foreach($_POST as $name=>$value) {
echo "$name $value \n";
}
Firebug输出请求:
POST http /frontend/save_layout.php 200 OK 186ms jquery....min.js (Zeile 4) HeaderPostAntwortHTML Parameterapplication/x-www-form-urlencoded bigip1.local 470/390 Quelle bigip1.local=470/390
Firebug输出(响应):
bigip1_local 470/390
正如您所看到的那样 - 它似乎正确地发送到服务器,但是一旦阅读$_POST
我们就在服务器上 - '.'
突然发现'_'
希望有人可以帮助我!
答案 0 :(得分:3)
您不应手动将data
转换为字符串。 jQuery做到了。只需将对象而不是字符串传递给Ajax函数。
你永远不应该(从不!)使用escape()
。此功能已中断,没有理由使用它。如果您出于某种原因必须进行手动URL编码,请在其位置使用encodeURIComponent()
。
function xy(nodes) {
$.each(nodes, function (i, node) {
$.post("save_layout.php", {
title: node.title,
x: node.translate.x,
y: node.translate.y
})
.done(function (output) {
$("#output").html(output);
})
.fail(function (response, status, error) {
alert("error" + response.responseText);
});
});
}
另请注意我对您的代码所做的一些其他更改,以使其在jQuery的上下文中更具惯用性:
nodes
作为参数而不是全局变量传入的事实。这使得功能更加独立。$.each()
替换你的for循环。$.post()
代替更通用的$.ajax()
。title
,x
,y
都是相同的。这使得服务器端(客户端上的和)更容易。.done()
和.fail()
回调可以附加到.post()
,.get()
和.ajax()
,因为它们的性质属于许。您可以read more about $.Deferred
and promises或者只是按原样使用它 - 一种在jQuery中使用Ajax回调的非常方便的方法。 您可能想要考虑将代码重构为使用所有对象生成一个 Ajax请求而不是每个对象的一个请求。 HTTP请求需要时间,最好将它们组合起来。
答案 1 :(得分:0)
你的情况就是使用jQuery功能
for (var i = 0, l = nodes.length; i < l; i++) {
var data = {};
data[nodes[i].title] = nodes[i].translate.x + "/" + nodes[i].translate.y;
$.ajax({
url: 'save_layout.php',
data: data,
dataType: "text",
type: 'post',
success: function(output) {
$("#output").html(output);
},
error: function (response, status, error) {
alert("error" + response.responseText);
}
});
}
答案 2 :(得分:-1)
在您的javascript代码中,您可以尝试使用
JSON.stringify(values);
然后只是你的php中的json_decode()。