Answer the question
In order to leave comments, you need to log in
JavaScript does not receive PHP arrays in JSON format. How to fix it?
Good afternoon forum users,
I created two files: index.php (client side) and server.php (server).
The code is as follows:
Client side:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$( "select [name='country']" ).bind("change", function () {
$("select[name='city']").empty();
$.get(
"server.php",
{country: $("select[name='country']").val()},
function (data){
data = JSON.parse(data);
for(var id in data){
$("select[name='city']").append($("<option value='"
+ id + "'>" + data[id] + "</option>"));
}
}
);
});
});
</script>
</head>
<body>
<label>Укажите страну:</label>
<select name="country">
<option value="0" selected="selected"></option>
<option value="1">Америка</option>
<option value="2">Франция</option>
</select>
<label>Города</label>
<select name="city">
<option value="0"></option>
</select>
</body>
</html>
<?php
if ($_GET["country"] == 1) {
echo json_encode (array("1"=>"Вашингтон", "2"=>"Сиэтл"));
}
else if ($_GET["country"] == 2) {
echo json_encode (array("1"=>"Париж", "2"=>"Марсель"));
}
?>
Answer the question
In order to leave comments, you need to log in
well, what do you want by passing an associative array to the serialization?
either declare a regular array array("Paris", "Marseille"), or work with the resulting object on the client side
. UPD: in the selector $( "select [name='country']" ).bind you have an extra space after select
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question