json_encode(字符串)给出反斜杠作为响应


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"fiddle"

您可能在不想的地方生成"或"。

不确定它是否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/en/function.urlencode.php

http://php.net/manual/en/function.urldecode.php

只需解码数组并在另一侧对其进行编码。