JS json在PHP上收到解密错误

I sent a JSON string from Javascript and received it on PHP, however my PHP script is not receiving it as JSON.

The JS generates this output:

{"id_own":"Metztli Alonso","tick":"123456","ticket":"TID","comm":"test viernes nnuevo formato php","NQueues":"AMX-GI-Administracion-Interna","NCauses":"Capacitacion"}

But the PHP receives this:

id_own=Metztli+Alonso&tick=123456&ticket=TID&NQueues=AMX-GI-Administracion-Interna&NCauses=Capacitacion&comm=test+viernes+nnuevo+formato+php

JS

//var obj = { id_own: f.id_own.value, tick: f.Ticket.value, ticket: TTYPE, comm: f.comments.value, NQueues: f.que.value, NCauses: f.cau.value };

//Sample data
var obj = { id_own: "Metztli Alonso", tick: "123456", ticket: "TID", comm: "test viernes nnuevo formato php", NQueues: "AMX-GI-Administracion-Interna", NCauses: "Capacitacion" };

const myJSON = JSON.stringify(obj);

alert(myJSON);

const xhr = new XMLHttpRequest();
xhr.open("POST","http://*****/dev_insert.php");
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(myJSON);

PHP

<?php
echo "<br>";
echo "mensaje de js";
$requestPayload = file_get_contents("php://input");
var_dump ($requestPayload);
</div>

The code you've provided, as it, won't do that.

The symptoms that you describe indicate that you are collecting the data from a form and running the JavaScript when the form is submitted, but not cancelling the default behaviour of the submit event.

Consequently:

  1. The submit event fires
  2. The JavaScript runs and initiates the Ajax request
  3. The JavaScript finishes
  4. The form submits … and URL encodes the data in it as you describe
  5. The Ajax request is cancelled because the environment it is running in is going away
  6. The browser renders the response to the form request

You need to prevent the default behaviour of the form submission:

form.addEventListener("submit", event => {
    event.preventDefault();
    // Then do everything you were already doing
});