Reputation: 13
I have seen many examples and I have used this myself in many of my programs but for some reason this doesn't want to work today.
I have JSON data that I can show in console.log
but it is unusable in my select
. I get this error in my console:
Cannot use 'in' operator to search for '76' in {"hello1":"hello1","hello2":"hello2"}
This is my code:
$.get("JSON.php?value=two", function(response) {
console.log(response);
// this is what my JSON returns
// {"hello1":"hello1","hello2":"hello2"}
if (response != '') {
$('#dropdown').find('option').remove();
$.each(response,function(key, value){
$('#dropdown').append('<option value=' + key + '>' + value + '</option>');
});
}
)};
Upvotes: 0
Views: 4598
Reputation: 13
Solution
Worked when Array was converted to Object
$.get("JSON.php?value=two", function(response)
{
console.log(response);
// this is what my JSON returns
// {"hello1":"hello1","hello2":"hello2"}
if (response != '')
{
var response2 = JSON.parse(response);
$('#dropdown').find('option').remove();
$.each(response2,function(key, value){
$('#dropdown').append('<option value=' + key + '>' + value +
'</option>');
});
}
)};
Upvotes: 0
Reputation: 11861
I just tested this successfully
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
var response = {"hello1":"hello1","hello2":"hello2"} ;
$('#dropdown').find('option').remove();
$.each(response,function(key, value){
$('#dropdown').append('<option value=' + key + '>' + value + '</option>');
});
});
</script>
</head>
<body>
<select id="dropdown"></select>
</body>
</html>
Please check. You will get something
Upvotes: 1
Reputation: 672
To achieve this your response should be an Array of Objects.
[
{
hello1 : "hello1"
},
{
hello2 : "hello2"
}
]
Upvotes: 0