2017-10-16 6 views
0

Avec l'ancienne méthode $ .ajax j'envoyer des tableaux et des données normales comme ceci:XMLHttpRequest - envoyer des tableaux par _POST

var dataARR = { 
    byteValue: 1, 
    data: [] 
}; 

Remarque data est un tableau.

dataARR.data.push({Username: "wazo", Info: "wazoinfo"}); 
dataARR.data.push({Username: "bifo", Info: "bifoinfo"}); 

Ensuite, pour qu'il soit prêt et l'envoi:

var dataJSON = JSON.stringify(dataARR); 
$.ajax({ 
    type: "POST", // This for array 
    url: "login.php", 
    cache: false, 
    data: { myJson: dataJSON }, 
    success: function (data) { 
     // Do stuff here 
    } 
}); 

Dans le code php je puis procédez comme suit:

$dataTotal = json_decode($post['myJson'], true); 
$Username0 = $dataTotal['data'][0]['Username']; 
$Info0 = $dataTotal['data'][0]['Info']); 
$Username1 = $dataTotal['data'][1]['Username']; 
$Info1 = $dataTotal['data'][1]['Info']); 

Tout cela a bien fonctionné.

Cependant, maintenant je suis en train de changer de XMLHttpRequest:

var url = "login.php"; 
var method = "POST"; 
var xhr = new XMLHttpRequest(); 
if ("withCredentials" in xhr) { 
    // XHR for Chrome/Firefox/Opera/Safari. 
    xhr.open(method, url, true); 
} else if (typeof XDomainRequest != "undefined") { 
    // XDomainRequest for IE. 
    xhr = new XDomainRequest(); 
    xhr.open(method, url); 
} else { 
    // CORS not supported. 
    xhr = null; 
} 

if (!xhr) { 
    return; 
} 
// Response handlers. 
xhr.onload = function (data) { 
    // Do stuff 
}; 

Et peu importe

var dataJSON = JSON.stringify(dataARR); 
xhr.send({ myJson: dataJSON }); 

Mais maintenant, le $_POST['myJson'] n'existe pas

Quand je fais un echo print_r($_POST);, retourne Array()1

Question: Que dois-je envoyer xhr.send(????); pour l'obtenir afin que je puisse lire à nouveau les tableaux dans php?

Répondre

0

Vous accédez aux données différemment avec XMLHttpRequest.

Dans le javascript:

var dataJSON = JSON.stringify(dataARR); 
xhr.send(dataJSON); 

Dans le php:

$dataTotal = json_decode(file_get_contents("php://input"), true); 
$Username0 = $dataTotal['data'][0]['Username']; 
$Info0 = $dataTotal['data'][0]['Info']); 
$Username1 = $dataTotal['data'][1]['Username']; 
$Info1 = $dataTotal['data'][1]['Info']);