[英]jquery/js and php communication issue
我正在使用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
就在服務器上 - '.'
突然是'_'
。
希望有人可以幫助我!
您不應手動將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()
因為它們的性質是一個承諾的。 你可以閱讀更多關於$.Deferred
和promises的信息,或者只是按$.Deferred
閱讀 - 這是在jQuery中使用Ajax回調的一種非常方便的方法。 您可能想要考慮將代碼重構為使用所有對象發出一個 Ajax請求而不是每個對象發出一個請求的內容。 HTTP請求需要時間,最好將它們組合起來。
你的情況只是使用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); } }); }
在您的JavaScript代碼中,您可以嘗試使用
JSON.stringify(values);
然后只是你的PHP中的json_decode()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.