1

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

3
  • 1
    Add dataType: 'json' to the $.ajax() call. Commented Jun 3, 2015 at 12:49
  • Add dataType:'json' to your ajax call Commented Jun 3, 2015 at 12:49
  • Use JSON.stringify at server side and use JSON.parse in successhandler to access the indices of the data. Commented Jun 3, 2015 at 12:49

2 Answers 2

3

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);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

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);
    }
});

1 Comment

the contentType is likely not required. contentType is the type of data your sending, not receiving.

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.