1 - how to read the object
The object sent by Ajax will be available in $_POST as a multi-dimensional array
2 - how to iterate the object is received
Whereas the following object dados
that will be sent by POST with jQuery.ajax()
, through property data
.
var dados = {
data: [
{name: 'foo'}
, {name: 'bar'}
, {name: 'baz'}
]
, paging: {
current: 1
, total: 10
}
};
On the server. You should iterate as follows:
<?php
$dados = $_POST['data'];
// array de objetos será recebido como array multidimensional
foreach ($dados as $dado) {
// acessando propriedade do objeto
// dados recebidos como array
$dado['name'];
}
$paging = $_POST['paging'];
// acessando propriedade do objeto
// objeto será recebido como array
$paging['current'];
$paging['total'];
3 - how to download files
You need to use several relatively new HTML5 API objects, so it may result in errors in old/outdated or IE browsers. It’s them: Blob, URL and attribute download of <a>
.
$.ajax({
type: 'POST',
url: 'gerararquivo.php',
data: dados,
dataType: 'json',
success: function(file) {
var a = document.createElement('a'), blob, url;
if (typeof a.download === 'undefined') {
alert('download não suportado pelo navegador');
} else {
// criar "arquivo", conteúdo como array e tipo como objeto
blob = new Blob([file], {type: 'text/plain'});
// criar URL para arquivo criado
url = URL.createObjectURL(blob);
a.href = url;
// atribuir nome de download do arquivo
a.download = 'nome_de_download.txt';
// fazer download
a.click();
// revogar URL criada
URL.revokeObjectURL(url);
}
}
});
It is also possible to store the file on the server as suggested in the comments, in which case the concern should be with concurrent requests.
Complicated without analyzing the structure of this object, you can post an example of this object received via ajax?
– Adir Kuhn
You are trying to retrieve the payload sent to you take a look at this question http://stackoverflow.com/questions/9597052/how-to-retrieve-request-payload
– Hiago Souza