如何从javascript发布JSON到php [复制]

This question already has an answer here:

I encoded an array into JSON in javascript:

var data = JSON.stringify(cVal);

And here is my ajaxrequest object:

function ajaxRequest(url, method, data, asynch, responseHandler){
var request = new XMLHttpRequest();
request.open(method, url, asynch);
if (method == "POST")
    request.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
request.onreadystatechange = function(){
if (request.readyState == 4) {
    if (request.status == 200) {
        responseHandler(request.responseText);
        }
    }
};
request.send(data);
}

and I send the json to php with this ajaxrequset:

ajaxRequest("setOrder.php","POST", data , true , dosetOrder);

in php side:

$array=$_POST['data'];

but system says that the data in a undefined index in php

</div>

Create an object and stringify to json

var data = {};
data["username"] = username;
data["password"] = password;
var jsonData = JSON.stringify(data);

Send it to your endpoint

function ajaxRequest(url, method, data, asynch, responseHandler){
  var request = new XMLHttpRequest();
  request.open(method, url, asynch);
  if (method == "POST")
    request.setRequestHeader("Content-Type","application/json"); 
  request.onreadystatechange = function(){
    if (request.readyState == 4) {
      if (request.status == 200) {
        responseHandler(request.responseText);
      }
    }
    request.send(data);
}

decode it at your endpoint

plain PHP

$body = json_decode(file_get_contents("php://input"), true);
echo $body["username"];

Slim Framework PHP

//example with Slim PHP framework
$body = json_decode($app->request->getBody(), true);
echo $body["username"];