在php键中使用右方括号 [英] Using square right bracket in php key
问题描述
我正在尝试使用ajax发布字典.但是我在使用json和]"字符时遇到了一些问题.
I am trying to post a dictionary using ajax. But I have run into some problems with json and "]" character.
这是我的代码(javascript)示例:
Here's example of my code (javascript):
var dict = {"id":"patient","where":{"name[~]":"J"}};
$.post("./ajax.php",{data:dict},function(data){
});
还有ajax.php(此文件仅处理$ _POST数组中的json编码数据):
And ajax.php (this file just deals with the json encoded data in $_POST array):
$where = $_POST["data"]["where"];
基本上,我正在尝试将json格式的消息发送到php,并且我想在其中处理数据.
Basically i am trying to send json format message to php, and there I want to process with the data.
我尝试了与json_encode的所有组合,并在php端进行了解码,在javascript端也尝试了JSON.stringify(),并尝试在右括号中使用转义字符.
I tried whole bunch of combination with json_encode and decode on php side, also JSON.stringify() on javascript side, tried to use escape characters with the right bracket.
但是当我转储$ _POST ["data] [" where]时,值为"J",键为"name [〜",而不是" name [〜].右括号从键中消失.
But when I dump $_POST["data]["where] there's value "J" with key "name[~" and not "name[~]". Right bracket disappears from the key.
有人有什么建议吗? 感谢您的帮助,我已经为此苦苦挣扎了几个小时...
Anyone having any advice, please? Thanks for help, I've been struggling with this for hours...
//我已经弄清楚,放在]"之后的所有内容都会从键中消失.因此,密钥将从"name [〜] asdf"->"name [〜" ......
// I've figured out, that everything i place after "]" disappears from the key. So the key transforms from "name[~]asdf" -> "name[~"...
推荐答案
当您向jQuery AJAX函数提供对象时,它将对其进行URL编码. jQuery将data.where
参数发送为:
When you provide an object to the jQuery AJAX functions, it URL-encodes it. jQuery is sending the data.where
parameter as:
data[where][name[~]]=J
和PHP显然不能处理这样的嵌套括号;它只是将[
之前的[
与下一个]
匹配.
and PHP apparently can't deal with nested brackets like that; it just matches the [
before name
with the next ]
.
也许jQuery需要对该属性名称进行双重编码以保护它,但显然不是.
Probably jQuery needs to double-encode this property name to protect it, but obviously it doesn't.
解决方法是将dict
编码为JSON,然后在PHP中对其进行解码. JS:
The workaround is to encode dict
as JSON, and decode it in PHP. JS:
$.post("./ajax.php",{data: JSON.stringify(dict)},function(data){
PHP:
$data = json_decode($_POST['data'], true);
$where = $data['where'];
var_dump($where);
这篇关于在php键中使用右方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!