elreeda
elreeda

Reputation: 4597

Error getting json data, ajax

I'm trying to get a data from server without refreshing the page using ajax, So the problem the data come like a text not like json data

my code:

$.ajax({
    type: "GET",
    url: "http://localhost:8080/search?key=" + QUERY + "",
    success: function (reslt) {
        console.log(reslt);
        console.log(reslt.length);
    }
});

and the data on the server:

im using nodejs and express framework the code:

router.get('/search', function (req, res) {
    tab = ['08:00', '09:00', '10:00', '11:00'];
    res.end(JSON.stringify(tab));
});

why when i do console.log(reslt[3]); it's give me 8 , should give me 10:00

Upvotes: 1

Views: 197

Answers (2)

Abhinav
Abhinav

Reputation: 8168

You have to use dataType and contentType attribute in your ajax request

$.ajax({
    type: "GET",
    dataType: 'json',
    contentType: "application/json",
    url: "http://localhost:8080/search?key=" + QUERY + "",
    success: function (reslt) {
        console.log(reslt);
        console.log(reslt.length);
    }
});

Upvotes: 0

Zee
Zee

Reputation: 8488

Use

dataType: 'json'

If your response is JSON, always set the datatype to json. Do it like this

$.ajax({
    type: "GET",
    dataType: 'json',
    url: "http://localhost:8080/search?key=" + QUERY + "",
    success: function (reslt) {
        console.log(reslt);
        console.log(reslt.length);
    }
});

Upvotes: 3

Related Questions