I am pulling in JSON data to populate two separate select fields (country and city).
When submitting the form I get the:
Cannot read property 'value' of undefined
I have tried resetting the data using:
data.countries = data[0];
data = data[0];
before / after and it returns:
Uncaught TypeError: Cannot read property 'length' of undefined
Here is a snippet of the code I am using to retrieve the data
$.ajax({
url: myAPI,
type: 'POST',
success: function (data) {
$.each(data.countries, function (index, value) {
country.append('<option value="' + value.name + '">' + value.name +'</option>');
});
country.on('change', function() {
var self = $(this).val();
city.find('option').remove();
for(var i = 0; i < data.countries.length; i++) {
if(data.countries[i].name == self) {
$.each(data.countries[i].metroAreas, function (index, value) {
city.append('<option value="' + value.name+'">' + value.name +'</option>');
});
}
}
});
}
});
You should to tell jQuery to parse the result as JSON using the dataType
option .
When omitted jQuery will guess the data type based on the Content-Type
response header. It's a common problem that the server doesn't set this header or is setting it incorrectly (eg to text/html
).
$.ajax({
url: myAPI,
type: 'POST',
dataType: 'json',
success: function (data) {
$.each(data.countries, function (index, value) {
country.append('<option value="' + value.name + '">' + value.name +'</option>');
});
country.on('change', function() {
var self = $(this).val();
city.find('option').remove();
for(var i = 0; i < data.countries.length; i++) {
if(data.countries[i].name == self) {
$.each(data.countries[i].metroAreas, function (index, value) {
city.append('<option value="' + value.name+'">' + value.name +'</option>');
});
}
}
}); }
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.