我想傳遞一個字符串化JSON對象作爲一個GET參數,但接收URL似乎無法對其進行解碼,我不知道爲什麼。
下面是相關代碼:
客戶端的JSON對象生產(工作正常):
function createJson(){
// This works fine. It creates a json objects with three elements, the third being an array.
//(omitted code for brevity)
return jsonData;
}
客戶端AJAX調用(正常工作):
function recordSetGet(jsonData){
request = createRequest();
var rawSet=JSON.stringify(jsonData);
var encodedSet=encodeURIComponent(rawSet);
var params="set="+encodedSet;
var url= "Ajax_recordSetGet.php?"+params;
request.open("GET", url, true);
request.onreadystatechange = function(){}
request.send(null);
}
這產生以下網址:Ajax_recordSetGet.php?set=%7B%22setTitle%22%3A%22test%22%2C%22setTags%22%3A%22test%20%22%2C%22set%22%3A%5B%7B%22first%22%3A%22Joe%22%2C%22last%22%3A%22Doe%22%2C%22checked%22%3Atrue%7D%5D%7D"
服務器端處理:
<?php
header('Content-Type:text/html; charset=UTF-8');
if(!session_id()){
session_start();
}
if(isset($_GET['set'])){
$set=$_GET['set'];//This is the URI encoded string
var_dump ($set);
var_dump (json_decode($set));
var_dump ("Json last error is ".json_last_error());
}
?>
的var_dumps的結果是: string '{"setTitle":"test","setTags":"test ","set":[{"first":"Joe","last":"Doe","checked":true}]}"' (length=90)
null
string 'Json last error is 4' (length=20)
那麼,爲什麼json_decode()
這裏失敗? json_last_error()
結果表明語法錯誤。
編輯:
如果我建立帕拉姆字符串沒有這樣的編碼是:需要注意的是json_decode如果我發送一個非編碼字符串也沒有
var rawSet=JSON.stringify(jsonData);
var params="set="+rawSet;
var url= "Ajax_recordSetGet.php?"+params;
然後URL成爲Ajax_recordSetGet.php?set={"setTitle":"test","setTags":"test ","set":[{"first":"Joe","last":"Doe","checked":true}]}"
並且接收URL var_dump產生相同的錯誤:
string '{"setTitle":"test","setTags":"test ","set":[{"first":"Joe","last":"Doe","checked":true}]}"' (length=90)
null
string 'Json last error is 4' (length=20)
請結識[The SSCCE](http://sscce.org/)。 –
** TL; DR **。嘗試讓你的問題更簡潔。如果我們需要更多,我們會問。 –
這是很多我沒看過的代碼。 –