Sinal
Sinal

Reputation: 1165

jQuery getJSON problem

$.getJSON( "http://yoolk.dev:3012/categories?callback=?", function(data) {
    console.log(data)
 }
);

I have the code above in order to get json data, but callback function seems not be working. Anyone can help? Thanks

Upvotes: 0

Views: 772

Answers (1)

jspcal
jspcal

Reputation: 51934

if the request fails, your callback wont be called. you can use something like the example below to detect the failure. jquery will not call any error handlers in case of a jsonp failure... so, one can implement a timer that checks the result...

here, task.run does the ajax request, and the checkStatus function checks the result.

var task = {
  complete: 0,
  timeout: 5000,

  run: function() {
    $.ajax({
      type: 'get',
      url: 'http://www.yahoo.com',
      dataType: 'jsonp',
      timeout: this.timeout,
      complete: function(req, status) {
        this.complete = 1
        if (status == "success") {
          alert('Success');
        } else {
          alert('Error: ' + status)
        }
      }
    })

    var o = this
    setTimeout(function() {o.checkStatus()}, this.timeout + 1000)
  },

  checkStatus: function() {
    if (!this.complete) {
      alert('Error: Request did not complete')
    }
  }
}

task.run()

Upvotes: 1

Related Questions