1

I'm a bit stuck, but this has to be user error; the following works, in a sense. It's adding new options to the select but there's a new option for every character in the JSON response, e.g.

Select form

{

[

"

N

a

m

e

"

:

and so on.

Firebug Lite logs the JSON response as:

{"d":"[{\"Name\":\"Monday\"},{\"Name\":\"Tuesday\"},{\"Name\":\"Wednesday\"}]"}

Here is the page source:

    <script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: '/MyWebService/MyWebService.asmx/GetDays',
            dataType: 'json',
            data: '{"_category":"Administration"}',
            success: function (response) {
                // Clear the list and add an instructional item...
                $("#FormsSelect").get(0).options.length = 0;
                $("#FormsSelect").get(0).options[0] = new Option("Select form", "-1");
                // Add each element returned from the server...
                $.each(response.d, function (index, category) {
                    $('#FormsSelect').append(
                    $('<option></option>').val(index).html(category)
                    );
                });
            },
            error: function (request, error) {
                alert("An error occurred: " + request.status + "\n" + request.responseText);
            }
        });
    });
</script>

Thoughts on why this is occurring?

Thanks, Aaron.

2 Answers 2

3

Notice how the response

"[{\"Name\":\"Monday\"},{\"Name\":\"Tuesday\"},{\"Name\":\"Wednesday\"}]"

is a string. If you loop through a string, you get it character by character.

If you want to parse the string as an array, you should do something like this, using the jQuery parseJSON method:

var arr = $.parseJSON(response.d);
$.each(arr, function(index, category) { 
 // ...

Also note that you probably want to do

.html(category.Name);

instead of

.html(category);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Peter, that's done the trick. If I had enough rep I'd mark this as the answer.
@Aaron Just press the green checkmark next to the answer if you don't have enough rep to upvote ;)
0

It should be:

$('<option></option>').val(index).html(category.Name)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.