菲尔(Phil)的出色回答,但自从OP标题说
从javascript( 不是jQuery )发送json对象到php
这是使用(原始)javascript的方法,以防万一有人寻找此方法:
var jsondata;var flickr = {'action': 'Flickr', 'get':'getPublicPhotos'};var data = JSON.stringify(flickr);var xhr = new XMLHttpRequest();xhr.open("POST", "../phpincl/apiConnect.php", !0);xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");xhr.send(data);xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { // in case we reply back from server jsondata = JSON.parse(xhr.responseText); console.log(jsondata); }}请注意 ,我们还需要服务器的响应转换成Javascript 对象 使用
JSON.parse()
现在,在服务器端(基于Phil的回答),如果您将响应发送回客户端,则可以执行以下操作:
header('Content-type: application/json');$json = file_get_contents('php://input');$json_depre = json_depre($json, true); $json_enpre = json_enpre($json_depre);echo $json_enpre;注意 :
首先解码然后再编码回原始json输入背后的原因是要在数据中的(可能的)URL中正确 转义 斜线,例如
json_enpre将转换此URL
http://example.com
进入
http://example.com
…这不是OP中的情况,但在其他一些情况下很有用。



