正在分析来自的JSONphp://input以及遍历对象


Parsing JSON from php://input and iterating through object

所以使用javascript I http.send一个php脚本一个字符串化的JSON,比如:

var http = new XMLHttpRequest();
http.open("POST", "./SubmitConfigJSON.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ConfigJSON="{"
ConfigJSON=ConfigJSON+"'""+document.getElementsByName("ConfigVars")[0].id+"'":'""+document.getElementsByName("ConfigVars")[0].innerHTML+"'"";
for (var i = 1; i < document.getElementsByName("ConfigVars").length; i++){
  ConfigJSON=ConfigJSON+",'""+document.getElementsByName("ConfigVars")[i].id+"'":'""+document.getElementsByName("ConfigVars")[i].innerHTML+"'"";
};
ConfigJSON=ConfigJSON+"}"
http.send(ConfigJSON);

JSON本身很简单。。。类似这样的东西:

{"username":"joebob","nocfilelocation":"noc1.xmp"}

并将其发送到一个PHP脚本,目的是该PHP脚本将

  1. 将JSON导入对象或数组
  2. 遍历对象或数组,将值写入到具有上述值的键名称的文件中

不知怎么的,在充实这个PHP的过程中,我已经把自己逼到了一个角落!

这项工作:

<?php
//writes the json string to a file
$ConfigJSON = json_decode(file_get_contents('php://input'));
$myfile = fopen("dropfile", "w") or die("Unable to open file!");
fwrite($myfile, $ConfigJSON);
fclose($myfile);
//imports a json string from a file and iterates through it, writing values to files with filenames based on their keys.
$ConfigJSON = json_decode(file_get_contents('./dropfile'));
foreach ($ConfigJSON as $key => $value){
  $myfile = fopen("$key", "w") or die("Unable to open file!");
  fwrite($myfile, $value);
  fclose($myfile);
};
?>

但我更喜欢只导入PHP输入,然后迭代,而不在其间写入文件。类似。。。

$ConfigJSON = json_decode(file_get_contents('php://input'));
foreach ($ConfigJSON as $key => $value){
  $myfile = fopen("$key", "w") or die("Unable to open file!");
  fwrite($myfile, $value);
  fclose($myfile);
};

但这不起作用。我肯定我错过了一些非常简单的东西。

如果file_get_contents('php://input')会产生您期望的JSON对象,那么您的代码在fwrite($myfile, $ConfigJSON)应该会失败得很惨。事实上,当你再次使用json_decode(file_get_contents('./dropfile'))时,它不会起作用,这只能意味着一件事:

您正在对JSON进行双重编码。

http.send()可能会对您的数据进行JSON编码。由于您已经在自己执行JSON.stringify(ConfigJSON),JSON编码的数据被封装在另一个JSON层中,这意味着您还需要json_decode两次才能取回对象。

提示:对所有相关变量使用var_dump($var)来检查其中的内容。不要猜测请参阅。要在AJAX请求中查看其结果,请查看浏览器的开发工具的网络检查器选项卡,并检查AJAX请求的详细信息。