Отправка многомерного массива JS в PHP через AJAX - PullRequest
0 голосов
/ 15 февраля 2019

У меня есть сайт электронной коммерции, и я пытаюсь настроить зоны доставки в США по штатам.Для этого я создал систему перетаскивания, в которой у нас есть 8 зон доставки, и вы можете просто перетаскивать состояния в соответствующую зону.

Это работает как ожидалось, но у меня есть несколько проблем:

  1. Когда вы перетаскиваете состояние в зону и перетаскиваете поверх него другое состояние, оно оказывается вложенным в это состояние, а не в зону перетаскивания, поэтому есть способ, если оно будет отброшенов другое состояние он добавляется в родительскую зону?JS line 9-12

  2. Когда я пытаюсь переслать это в мой PHP-скрипт, он не подбирается должным образом.console.log() перед битом ajax показывает многомерный массив так, как я хочу, но я получаю пустой ответ post_set_blank.

Для этого мой PHP-скрипт выглядит следующим образом:

if(isset($_POST['shipping_zone_array']) && $_POST['shipping_zone_array']!=""){
    echo 'session_set';
}else if(isset($_POST['shipping_zone_array'])){
    echo 'post_set_blank';
}else{
    echo 'not_posted';
}

Код:

function drag_start(event) {
	event.dataTransfer.dropEffect = "move";
	event.dataTransfer.setData("text", event.target.getAttribute('id'));
}

function drag_drop(event) {
	event.preventDefault();
	var elem_id = event.dataTransfer.getData("text");
	if(event.target.className == 'states'){
		console.log('in another state');
		event.target.parent.appendChild(document.getElementById(elem_id));
	}else{
		event.target.appendChild(document.getElementById(elem_id));
	}
}

var zone_1 = [];
var zone_2 = [];
var zone_3 = [];
var zone_4 = [];
var zone_5 = [];
var zone_6 = [];
var zone_7 = [];
var zone_8 = [];
var shipping_zone_array = [];

function readDropZone(){
	var shipping_zones = document.getElementsByClassName("shipping_zone");
	for(var i=1; i<=shipping_zones.length; i++){
		var shipping_zone = document.getElementById("shipping_zone_"+i);
		for(var j=1; j<=shipping_zone.children.length; j++){
			alert(shipping_zone.children[j].id);
			if(i==1){
				zone_1.push(shipping_zone.children[j].id);
			}else if(i==2){
				zone_2.push(shipping_zone.children[j].id);
			}else if(i==3){
				zone_3.push(shipping_zone.children[j].id);
			}else if(i==4){
				zone_4.push(shipping_zone.children[j].id);
			}else if(i==5){
				zone_5.push(shipping_zone.children[j].id);
			}else if(i==6){
				zone_6.push(shipping_zone.children[j].id);
			}else if(i==7){
				zone_7.push(shipping_zone.children[j].id);
			}else if(i==8){
				zone_8.push(shipping_zone.children[j].id);
			}
		}
	}
	shipping_zone_array['zone_1'] = zone_1;
	shipping_zone_array['zone_2'] = zone_2;
	shipping_zone_array['zone_3'] = zone_3;
	shipping_zone_array['zone_4'] = zone_4;
	shipping_zone_array['zone_5'] = zone_5;
	shipping_zone_array['zone_6'] = zone_6;
	shipping_zone_array['zone_7'] = zone_7;
	shipping_zone_array['zone_8'] = zone_8;
	
	console.log(shipping_zone_array);
	var formData = new FormData();
	formData.append("shipping_zone_array", shipping_zone_array);
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function(){
		if(this.readyState == 4 && this.status == 200){
			if(this.responseText.includes('session_set')){
				console.log('session_set');
			}else if(this.responseText.includes('post_set_blank')){
				console.log('post_set_blank');
			}else if(this.responseText.includes('not_posted')){
				console.log('not_posted');
			}
		}
	};
	xmlhttp.open("POST", "mypage.php", true);
	xmlhttp.send(formData);
}
.states{
	display:inline-block;
	background-color:#CCC;
	border:1px solid #999;
	border-radius:3px;
	width:100px;
	height:40px;
	margin:5px;
	padding:5px;
	text-align:center;
	vertical-align:middle;
	cursor:move;
}
.shipping_zone{
	display:inline-block;
	background-color:#EEE; 
	border:1px solid #999;
	border-radius:5px;
	width:650px; 
	height:220px;
	margin:5px;
	padding:5px;
	text-align:center;
	vertical-align:middle;
}
<table>
<tr>
	<td>
		<div id="shipping_zone_1" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 1<br /></div>
		<div id="shipping_zone_2" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 2<br /></div>
		<div id="shipping_zone_3" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 3<br /></div>
		<div id="shipping_zone_4" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 4<br /></div>
		<div id="shipping_zone_5" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 5<br /></div>
		<div id="shipping_zone_6" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 6<br /></div>
		<div id="shipping_zone_7" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 7<br /></div>
		<div id="shipping_zone_8" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 8<br /></div>
	</td>
	<td>
		<div id="AL" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Alabama</div>
		<div id="AK" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Alaska</div>
		<div id="AZ" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Arizona</div>
		<div id="AR" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Arkansas</div>
		<div id="CA" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">California</div>
		<div id="CO" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Colorado</div>
		<div id="CT" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Connecticut</div>
		<div id="DE" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Delaware</div>
		<div id="FL" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Florida</div>
		<div id="GA" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Georgia</div>
		<div id="HI" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Hawaii</div>
		<div id="ID" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Idaho</div>
		<div id="IL" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Illinois</div>
		<div id="IN" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Indiana</div>
		<div id="IA" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Iowa</div>
		<div id="KS" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Kansas</div>
		<div id="KY" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Kentucky</div>
		<div id="LA" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Louisiana</div>
		<div id="ME" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Maine</div>
		<div id="MD" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Maryland</div>
		<div id="MA" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Massachusetts</div>
		<div id="MI" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Michigan</div>
		<div id="MN" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Minnesota</div>
		<div id="MS" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Mississippi</div>
		<div id="MO" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Missouri</div>
		<div id="MT" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Montana</div>
		<div id="NE" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Nebraska</div>
		<div id="NV" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Nevada</div>
		<div id="NH" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">New Hampshire</div>
		<div id="NJ" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">New Jersey</div>
		<div id="NM" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">New Mexico</div>
		<div id="NY" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">New York</div>
		<div id="NC" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">North Carolina</div>
		<div id="ND" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">North Dakota</div>
		<div id="OH" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Ohio</div>
		<div id="OK" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Oklahoma</div>
		<div id="OR" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Oregon</div>
		<div id="PA" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Pennsylvania</div>
		<div id="RI" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Rhode Island</div>
		<div id="SC" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">South Carolina</div>
		<div id="SD" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">South Dakota</div>
		<div id="TN" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Tennessee</div>
		<div id="TX" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Texas</div>
		<div id="UT" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Utah</div>
		<div id="VT" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Vermont</div>
		<div id="VA" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Virginia</div>
		<div id="WA" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Washington</div>
		<div id="WV" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">West Virginia</div>
		<div id="WI" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Wisconsin</div>
		<div id="WY" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Wyoming</div>
	</td>
</tr>
</table>

<center>
<button onclick="readDropZone()">Get Object Data</button>
</center>

1 Ответ

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

Ваши зоны доставки HTML <div id="shipping_zone_1" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 1<br /></div> также содержит тег <br>.

Когда вы зацикливаетесь на дочерних элементах, for(var j=1; j<=shipping_zone.children.length; j++) {, вы также сталкиваетесь с тегом <br> внутри дочерней коллекции.

Когда вы запрашиваете идентификатор этого тега <br>, вы получаете сообщение об ошибке, поскольку у них нет идентификатора.В результате ваши массивы остаются пустыми.

Так что либо отфильтруйте узлы, которые не являются тегами <div>, либо используйте другой метод создания массива.

Я бы использовал простую функцию, которая сразу выбирает правильные теги - и толькоправильные теги, больше ничего - с помощью querySelector() ищите все элементы с классом .states внутри элемента зоны вместо getElementById() зоны, а затем зацикливайте дочерние элементы.

function drag_start(event) {
  event.dataTransfer.dropEffect = "move";
  event.dataTransfer.setData("text", event.target.getAttribute('id'));
}

function drag_drop(event) {
  event.preventDefault();
  var elem_id = event.dataTransfer.getData("text");
  if(event.target.className == 'states'){
    console.log('in another state');
    event.target.parentElement.appendChild(document.getElementById(elem_id));
  }else{
    event.target.appendChild(document.getElementById(elem_id));
  }
}
function get_states( zone_selector ) {
  return Array
    .from( document.querySelectorAll( `${ zone_selector } > .states`))
    .map( state => state.id );
}
function readDropZone(){
  var shippping_zones_object = {
    "shipping_zone_1": get_states( '#shipping_zone_1' ),
    "shipping_zone_2": get_states( '#shipping_zone_2' ),
    "shipping_zone_3": get_states( '#shipping_zone_3' ),
    "shipping_zone_4": get_states( '#shipping_zone_4' ),
    "shipping_zone_5": get_states( '#shipping_zone_5' ),
    "shipping_zone_6": get_states( '#shipping_zone_6' ),
    "shipping_zone_7": get_states( '#shipping_zone_7' ),
    "shipping_zone_8": get_states( '#shipping_zone_8' )
  };
  console.log( shippping_zones_object );
  // Continue with AJAX.
}
.states{
    display:inline-block;
    background-color:#CCC;
    border:1px solid #999;
    border-radius:3px;
    x-width:100px;
    x-height:40px;
    margin:5px;
    padding:5px;
    text-align:center;
    vertical-align:middle;
    cursor:move;
  }
  .shipping_zone{
    display:inline-block;
    background-color:#EEE; 
    border:1px solid #999;
    border-radius:5px;
    x-width:650px; 
    x-height:220px;
    margin:5px;
    padding:5px;
    text-align:center;
    vertical-align:middle;
  }
<table>
  <tr>
    <td>
    <div id="shipping_zone_1" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 1<br /></div>
    <div id="shipping_zone_2" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 2<br /></div>
    <div id="shipping_zone_3" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 3<br /></div>
    <div id="shipping_zone_4" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 4<br /></div>
    <div id="shipping_zone_5" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 5<br /></div>
    <div id="shipping_zone_6" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 6<br /></div>
    <div id="shipping_zone_7" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 7<br /></div>
    <div id="shipping_zone_8" class="shipping_zone" ondragenter="return false" ondrop="drag_drop(event)" ondragover="return false" ondragleave="return false" >Zone 8<br /></div>
    </td>
    <td>
    <div id="AL" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Alabama</div>
    <div id="AK" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Alaska</div>
    <div id="AZ" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Arizona</div>
    <div id="AR" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Arkansas</div>
    <div id="CA" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">California</div>
    <div id="CO" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Colorado</div>
    <div id="CT" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Connecticut</div>
    <div id="DE" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Delaware</div>
    <div id="FL" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Florida</div>
    <div id="GA" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Georgia</div>
    <div id="HI" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Hawaii</div>
    <div id="ID" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Idaho</div>
    <div id="IL" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Illinois</div>
    <div id="IN" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Indiana</div>
    <div id="IA" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Iowa</div>
    <div id="KS" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Kansas</div>
    <div id="KY" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Kentucky</div>
    <div id="LA" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Louisiana</div>
    <div id="ME" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Maine</div>
    <div id="MD" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Maryland</div>
    <div id="MA" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Massachusetts</div>
    <div id="MI" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Michigan</div>
    <div id="MN" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Minnesota</div>
    <div id="MS" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Mississippi</div>
    <div id="MO" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Missouri</div>
    <div id="MT" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Montana</div>
    <div id="NE" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Nebraska</div>
    <div id="NV" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Nevada</div>
    <div id="NH" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">New Hampshire</div>
    <div id="NJ" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">New Jersey</div>
    <div id="NM" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">New Mexico</div>
    <div id="NY" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">New York</div>
    <div id="NC" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">North Carolina</div>
    <div id="ND" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">North Dakota</div>
    <div id="OH" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Ohio</div>
    <div id="OK" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Oklahoma</div>
    <div id="OR" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Oregon</div>
    <div id="PA" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Pennsylvania</div>
    <div id="RI" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Rhode Island</div>
    <div id="SC" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">South Carolina</div>
    <div id="SD" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">South Dakota</div>
    <div id="TN" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Tennessee</div>
    <div id="TX" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Texas</div>
    <div id="UT" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Utah</div>
    <div id="VT" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Vermont</div>
    <div id="VA" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Virginia</div>
    <div id="WA" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Washington</div>
    <div id="WV" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">West Virginia</div>
    <div id="WI" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Wisconsin</div>
    <div id="WY" class="states" draggable="true" ondragstart="drag_start(event)" ondragend="return false">Wyoming</div>
    </td>
  </tr>
</table>
<button onclick="readDropZone()">Get Object Data</button>

PS : Если вы все еще хотите сделать два цикла for, .children дает мне только теги BR,Вам нужно .childNodes внутри ваших циклов for, если вы хотите сделать это таким образом.

PPS : если вы установите shipping_zone_array['zone_1'] = zone_1;, технически вы захотите объект с массивами в качестве свойств,вместо многомерного массива.Поэтому либо измените имя, либо используйте правильный синтаксис.

Мульти-массив будет:

[
 [ "IL", "MI" ],
 [],
 [],
 [],
 [],
 [],
 [],
 []
]

Объект будет:

{
  "zone_1': [ "IL", "MI" ],
  "zone_2': [ "IL", "MI" ],
  "zone_3': [ "IL", "MI" ],
  "zone_4': [ "IL", "MI" ],
  "zone_5': [ "IL", "MI" ],
  "zone_6': [ "IL", "MI" ],
  "zone_7': [ "IL', "MI" ],
  "zone_8': [ "IL", "MI" ]
}
...