[英]json_encode(string) giving backslashes in response
我正在用js創建對象數組,並將其字符串化后將其發送到我的一個控制器。
var arr = new Array();
for(i=0;i<noOfDeals;i++){
var deals = {'percentageMin':document.getElementById("pmin"+i).value,
'percentageMax':document.getElementById("pmax"+i).value,
'modelApplicable': document.getElementById("model"+i).value,
'maxCashback' : document.getElementById("maxcash"+i).value,
'dealId' : document.getElementById("deal"+i).value
};
arr.push(deals);
}
alert(JSON.stringify(arr));
$.ajax({method:'get',url:'abc?data='+JSON.stringify(arr),success:function(response) {
//response = JSON.parse(response);
response = JSON.parse(response);
alert(response.body);
response = JSON.parse(response.body);
if(response.status != undefined && response.status == 'SUCCESS') {
alert('Merchant details updated successfully. Refresh the page to see the changes.');
}
else {
alert('Could not update merchant details, Some Error Occurred');
}
}});
在我的控制器中,我正在編碼數據,然后發送以命中API:
public function updateselectedmerchants(){
if (isset($_GET['data'])) {
$str_data = $_GET['data'];
print_r(json_encode(array('deals' => $str_data)));
die;
}
}
輸出 :
{"deals":"[{\"percentageMin\":\"1.00\",\"perentageMax\":\"0.00\",\"modelApplicable\":\"3\",\"maxCashback\":\"30.00\",\"dealId\":\"7\"}"}
所需的輸出:
{"deals":[{\"percentageMin\":\"1.00\",\"perentageMax\":\"0.00\",\"modelApplicable\":\"3\",\"maxCashback\":\"30.00\",\"dealId\":\"7\"}]}
在即將出現的輸出中,有三件事是不需要的:
1) The double quotes before the first square brackets should not be there.
2) The ending square bracket is not present
3) "/" appearing
請幫我解決一下這個。
你應該做
$str_data = json_decode($_GET['data'], true);
print_r(json_encode(array('deals' => $str_data)));
否則, $str_data
仍然是一個字符串,並且將以此方式進行JSON編碼,而您似乎希望它成為一個PHP數組結構,然后將所有內容再次編碼為有效JSON。
看到這個PHP“小提琴”
您可能會在不需要的位置生成“或”。
不知道它是否可以100%工作,但是請嘗試:
public function updateselectedmerchants(){
if (isset($_GET['data'])) {
$str_data = json_decode($_GET['data']);
print_r(json_encode(array('deals' => $str_data)));
die;
}
}
您應該嘗試使用PHP方法:
http://php.net/manual/zh/function.urlencode.php
http://php.net/manual/zh/function.urldecode.php
只需解碼數組並在另一側對其進行編碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.