duckmike
duckmike

Reputation: 1036

Get JSON from web service using jQuery

So my javascript looks like:

    try {
        var response = $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "BudgService.asmx/LoadDetail",
            data: "{'building': '63170', 'CurrentYear':'2014'}",
            dataType: "json"
        });
        $.when(response).then(function () {
            loadData();
        });
    } catch (err) {
        alert(err);
    }

    function LoadData() {
        alert('here');
    }

And web service

    [ScriptMethod]
    public string LoadDetail(string building, string CurrentYear) {
        return "[{color:\"red\", value: \"#f00\"}]";
    }

But I never get to the loadData function and nothing gets populated into response.

What am I missing?

Upvotes: 0

Views: 151

Answers (1)

Quentin
Quentin

Reputation: 944246

Your JSON is invalid.

For your response:

In JavaScript object literal syntax, property names may be strings or identifiers, but in JSON they must be strings.

"[{\"color\":\"red\", \"value\": \"#f00\"}]"

For your request:

In JavaScript, strings may be delimited with " or ' characters, but in JSON they must be delimited with " characters.

data: '{"building": "63170", "CurrentYear":"2014"}',

As a rule of thumb, it is better to build a native data structure and then use a JSON library to serialise it to JSON instead of trying to handcraft JSON.

Also, you can't include a request body in a GET request. You need to use POST.

Upvotes: 1

Related Questions