最安全的方式发送JSON字符串到PHP服务器


Safest way to send JSON string to PHP server

我一直在尝试发送JSON字符串到PHP服务器,像这样:

$.ajax({  
    type: "POST",  
    url: "themes.php?page=themeoptions",  
    data: {structure : JSON.stringify(structure)},    
});

但是,我发送的字符串中的每个引号都会自动转义,所以我无法在PHP中使用json_decode()解码它。我可以删除所有转义字符,但我真的怀疑这种发送JSON数据到服务器的方式是安全的。

所以,我想知道你是否对如何在简单的和安全(不一定是防弹)的方式做到这一点有任何想法?

谢谢!

你可以只写'{"structure":' + JSON.stringify(structure) + '}'{structure: structure}

第一个是JSON字符串,所以jQuery不需要解析它。第二个是一个javascript对象,所以jQuery知道如何解析它。

但是你把两者混在一起了,所以jQuery会混淆并重新编码你的对象,因为你只编码了一半的对象。

另一种选择是JSON.stringify({structure: structure })

试试这个

$.ajax({  
    type: "POST",  
    url: "themes.php?page=themeoptions",  
    data: {structure: structure},    
});
$.ajax({  
    type: "POST",  
    url: "themes.php?page=themeoptions",  
    data: structure,    
});

引用自文档:

dataObjectString

要发送到服务器的数据。它是如果不是字符串,则转换为查询字符串。它被附加到get请求的url。请参阅processData选项来防止这种情况自动处理。对象必须是键/值对。如果value是数组,jQuery序列化多个具有相同键的值传统设置的值(如下所述)。