2

Using jquery ajax request like this

$.ajax({
url: 'mydata.json',
type: 'get',
error: function(data){
},
success: function(data){
  data=jQuery.parseJSON(data);
  //do something with data              
    }
});

It is working perfect except when I implement it on server with a server url which internally generates json response object and return. then I don't need jQuery.parseJSON(data). Is there a way where I can use local json file and get response as json object?

4 Answers 4

3
$.ajax({
url: 'mydata.json',
type: 'get',
dataType: 'json',
error: function(data){
},
success: function(data){
  //do something with data              
    }
});

Specifying dataType: 'json' tells jQuery to expect JSON data and automatically parse it.

Sign up to request clarification or add additional context in comments.

Comments

0

I would recommend checking to see if the returned data has already been converted to a JSON object. If so, then there's no reason to parse it.

    $.ajax({ 
      url: 'mydata.json', 
      type: 'get', 
      error: function(data){ }, 
      success: function(data){ 
        console.log(data); //check to see if jQuery has already converted the response to a JSON object
        //data=jQuery.parseJSON(data); //do something with data
      }
    });

Comments

0

It's a know issue that success() callback won't fire on local jQuery.ajax. Use complete() instead if you intend to run the script locally. Also because of this issue, you should not use jQuery.getJSON for the job (because the function will only fire when success.)

Comments

0
$.getJSON('mydata.json').done(function(response) {
    console.log("Success");
}).fail(function() {
    console.log("Error");
});

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.