dojo newbie read json response from web service

2019-09-06 12:29发布

问题:

i have a webservice that is returning this response :

<string xmlns="http://tempuri.org/">{ "Head":[ { "ID":"1","Name":"David"} ]}</string>

when i try to get the response back, i keep getting the error : "missing ; before statement"

i am just starting to get into this so am probably doing something very wrong.

why is the response not working for me?

my dojo code looks like this

    var targetNode = document.getElementById("foo");

    var def = dojo.io.script.get({
        url: "http://localhost/WebData/PublicData.asmx/HelloWorld",
        timeout: 30000,
        handleAs: "json",
        preventCache: true,
        handle: function(error, ioargs) {
            var message = "";
            switch (ioargs.xhr.status) {
                case 200:
                    message = "Good request.";
                    break;
                case 404:
                    message = "The requested page was not found";
                    break;
                case 500:
                    message = "The server reported an error.";
                    break;
                case 407:
                    message = "You need to authenticate with a proxy.";
                    break;
                default:
                    message = "Unknown error.";
            }
            targetNode.innerHTML = message;
        }
    });

thanks! david

回答1:

Your server's response mixes XML-like data (<string xmlns="http://tempuri.org/">)with JSON.

For dojo to handle the response using handleAs: 'json' you will need your server to return pure JSON data only, i.e just

{ "Head":[ { "ID":"1","Name":"David"} ]}

Failing that you would need to handle the response as text, strip out the tags and then parse just the JSON content. As a general tip "missing ; before statement" usually means mal-formed JSON.

EDIT

I just noticed the first argument to your handle function is "error". The first argument to the handle function contains the server's response (In this case a javascript object based on the JSON received.).