php json_decode挂起,无法从POST解码字符串

时间:2018-01-23 03:53:34

标签: javascript php json

我是PHP,JSON,js的新手。

我有一个将JSON字符串发送给PHP的js程序 在PHP中使用json_decode fn时遇到一些问题 我尝试将JS中的字符串接收保存到文件中,并且json字符串是正确的,没有任何问题。 但是当我尝试使用json_decode时,函数会挂起(我想,因为函数调用之下的任何东西都没有被调用,所有我的echo / print都没有给出任何东西。

以下是我的js代码:

function post()
{
  var test1 = {
    name:"marzzuq",
    age:16
  };
  myjson = JSON.stringify(test1);
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("POST","post.php",true);
  xmlhttp.setRequestHeader("Content-type","application/json");
  xmlhttp.send(myjson);
  console.log("\nsend ok: " + myjson);
}

以下是我的php脚本:

<?php
 $rawdata = file_get_contents('php://input');
 file_put_contents('/tmp/test.json', $rawdata);
 $jsson = json_decode($rawdata);
 file_put_contents('/tmp/test3.json', $jsson);
 `echo test >> /tmp/test.txt`;
 ?>

我尝试过使用htmlentities和html_entity_decode:
$result= htmlentities((string)$rawdata);
$result2 = html_entity_decode((string)$rawdata);

并在json_decode上使用结果但不起作用。
长度fr $rawdata是27(使用strlen),这是正确的。

我尝试打印json_last_error,但就像我说的那样,json_decode行下面的所有代码都停止工作,所以什么都不会打印出来。

switch (json_last_error()) {
    case JSON_ERROR_NONE:
        `echo ' - No errors' >> /tmp/test.txt`;
    break;
    case JSON_ERROR_DEPTH:
        `echo ' - Maximum stack depth exceeded' >> /tmp/test.txt`;
    break;
    case JSON_ERROR_STATE_MISMATCH:
        `echo ' - Underflow or the modes mismatch' >> /tmp/test.txt`;
    break;
    case JSON_ERROR_CTRL_CHAR:
        `echo ' - Unexpected control character found' >> /tmp/test.txt`;
    break;
    case JSON_ERROR_SYNTAX:
        `echo ' - Syntax error, malformed JSON' >> /tmp/test.txt`;
    break;
    case JSON_ERROR_UTF8:
        `echo ' - Malformed UTF-8 characters, possibly incorrectly encoded' >> /tmp/test.txt`;
    break;
    default:
        `echo ' - Unknown error' >> /tmp/test.txt`;
    break;
}

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

这就是我在PHP中解码JSON的方法。这也是一个MySQL插件。我想你可能想对你刚刚在PHP中收到的数据做些什么。

首先,表单数据我序列化

来自html表单的键值对的序列化数组。

var data = [
{
"name":"CLIENT_ID",
"value":"111"
},
{
"name":"PROJECT_ID",
"value":"222"
},
{
"name":"USER_ID",
"value":"465605"
},
{
"name":"UTL_LATITUDE",
"value":"40.6110589"
},
{
"name":"UTL_LONGITUDE",
"value":"-111.8999353"
},
{
"name":"UTL_EVENT",
"value":"CLOCK IN"
},
{
"name":"UTL_ACTION",
"value":"MEETING"
}
];

将其字符串化以提交给PHP ...

php_decode函数期望这种格式的JSON。

[{"name":"CLIENT_ID","value":"111"},{"name":"PROJECT_ID","value":"222"},{"name":"USER_ID","value":"465605"},{"name":"UTL_LATITUDE","value":"40.6110589"},{"name":"UTL_LONGITUDE","value":"-111.8999353"},{"name":"UTL_EVENT","value":"CLOCK IN"},{"name":"UTL_ACTION","value":"TRAVEL"}]

<?php
/* Status Codes

return 0 = Nothing to Update (n/a)
return 1 = Successful Insert Query
return 2 = Database Connection refused
return 3 = MySQL Query Error OR Wrong URL Parameters */

/* Disable Warnings so that we can return ONLY what we want through echo. */
mysqli_report(MYSQLI_REPORT_STRICT);

// First get raw POST input
$raw_post     = file_get_contents('php://input');
// Run through url_decode..
$url_decoded  = urldecode($raw_post);
// Run through json_decode...
$json_decoded = json_decode($url_decoded, false); // false to allow for reference to oject. eg. $column->name instead of $column["name"] in the foreach.

$client_id      = (strlen($json_decoded[0]->value) > 0 ? $json_decoded[0]->value : null);
$project_id     = (strlen($json_decoded[1]->value) > 0 ? $json_decoded[1]->value : null);
$user_id        = (strlen($json_decoded[2]->value) > 0 ? $json_decoded[2]->value : null);
$utl_latitude   = (strlen($json_decoded[3]->value) > 0 ? $json_decoded[3]->value : null);
$utl_longitude  = (strlen($json_decoded[4]->value) > 0 ? $json_decoded[4]->value : null);
$utl_event      = (strlen($json_decoded[5]->value) > 0 ? $json_decoded[5]->value : null);
$utl_action     = (strlen($json_decoded[6]->value) > 0 ? $json_decoded[6]->value : null);

// INCLUDE DB CONNECTION STRING
//include 'php_pdo_mysql_connect.php';

mysqli_report(MYSQLI_REPORT_STRICT);

$host = 'localhost';
$db   = 'alpha1';
$user = 'root';
$pass = 'password';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES   => false,
];

try {

$link = new PDO( $dsn, $user, $pass, $opt ); 

return $link;

} catch( PDOException $e) {

// Any error at this point...
$originalError = $e->getCode();

// MySQL Database connection refused..
if ($originalError == '2002') {

// Custom error.
echo '2';
exit;

}

}

// SQL INSERT query...
$stmt = $link->prepare("

INSERT INTO tbl_user_time_log 

( 
    CLIENT_ID, 
    PROJECT_ID,
    USER_ID,
    UTL_LATITUDE,
    UTL_LONGITUDE,
    UTL_EVENT,
    UTL_ACTION
)

VALUES 

( 

:client_id,
:project_id,
:user_id,
:utl_latitude,
:utl_longitude,
:utl_event,
:utl_action

) 

");

// Bind the corresponding parameter.
$stmt->bindParam(':client_id', $client_id, PDO::PARAM_INT);         // INT
$stmt->bindParam(':project_id', $project_id, PDO::PARAM_INT);       // INT
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);             // STR

$stmt->bindParam(':utl_latitude', $utl_latitude, PDO::PARAM_STR);   // STR
$stmt->bindParam(':utl_longitude', $utl_longitude, PDO::PARAM_STR); // STR



$stmt->bindParam(':utl_event', $utl_event, PDO::PARAM_STR);         // STR
$stmt->bindParam(':utl_action', $utl_action, PDO::PARAM_STR);       // STR

// Execute this SQL statement.
$stmt->execute(); 

// Catch pk generated for this new record. 
// $pk_user_time_log_id = $link->lastInsertId();

$link = null;
$stmt = null;

// return 1 = Successful Insert Query
echo '1';

?>

答案 1 :(得分:0)

实际上主要问题是html字符,您可以使用 html_entity_decode()函数将所有实体转换为适用的字符!

json_decode(html_entity_decode('your variable here'));