Как получить доступ к массиву на другой странице после отправки через ajax - PullRequest
0 голосов
/ 15 апреля 2019

У меня есть массив student. Мне нужно передать этот массив на другой php-странице через POST, а не из GET, потому что он может содержать тысячи символов.

Я пытаюсь открыть новую страницу sheet.php и отобразить массив student, я просто проверяю echo $_POST['mnu'], но он показывает неопределенный индекс ошибка.

var http = null;
if(window.XMLHttpRequest){
    http = new XMLHttpRequest();
}
else{
    http = new ActiveXObject('Microsoft.XMLHTTP');
}
http.open('POST','sheet.php',true);
http.setRequestHeader('Content-type','application/x-www-form-urlencoded');
http.onreadystatechange = function(){
    if(http.readyState==4 && http.status==200){
        window.open('sheet.php','_blank')
    }
}
http.send('mnu='+JSON.stringify(student));

Ответы [ 2 ]

2 голосов
/ 15 апреля 2019

Как прокомментировал @RamRaider .. вы делаете два запроса к sheet.php.Первый - это «тихий» POST-запрос, а второй - запрос GET после успешного завершения первого POST-запроса.

Request count

Второй выигранный запросНе делитесь полезными данными первого.

Если я правильно понимаю, приведенный ниже код должен делать то, что вы хотите ...

// Create a form element
// <form action="sheet.php" method="post"></form>
var tempForm = document.createElement('form');
tempForm.setAttribute('action', 'sheet.php');
tempForm.setAttribute('method', 'POST');
tempForm.setAttribute('target', '_blank'); // Open in new tab

// Create an input field
// <input name="mnu" value="...">
var tempInput = document.createElement('input');
tempInput.setAttribute('name', 'mnu');
tempInput.setAttribute('value', JSON.stringify(student)); // Set field value

// Add the input to the form
tempForm.appendChild(tempInput);


// Add the form to the body in order to post
document.body.appendChild(tempForm);

// Submit the form
tempForm.submit();

// Remove the form
document.body.removeChild(tempForm);

И если вы используете jQuery, вы можетеупростить приведенный выше код ..

$('<form>', {
    action: 'sheet.php',
    method: 'POST',
    target: '_blank',
    html: $('<input>', {
        name: 'mnu',
        value: JSON.stringify(student)
    }).prop('outerHTML')
}).appendTo($('body')).submit().remove();

0 голосов
/ 15 апреля 2019

Измените http.send('mnu='+JSON.stringify(student)); на http.send(JSON.stringify(student));

И затем в вашем sheet.php используйте json_decode($_POST) для получения ваших POST данных

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...