Technipelago AB

Technipelago Blog Stuff that we learned...


Make sure you have the right Content-Type for JSON

Publicerad den 3 mar 2009

Yesterday I spent 4 hours debugging a YUI AutoComplete component that I put on my page via the Grails-UI plugin. The result container (drop down) was not expanded even though the AJAX request returned perfect formed JSON data.

It was not until I put a YAHOO logger on my page and put som extra logging statements in autocomplete-debug.js that I found the simple and stupid problem.

The content-type of my AJAX response was set to “text/json” instead of “application/json”.

I copied an example from the web and did not notice the wrong content type.

The content type “application/json” is registered with IANA but there are many examples out there with other content types for JSON data. Read the specification.

Happy to have found the problem, but very frustrated that I spent that many hours on it.

By the way: Grails make it really simple to render JSON responses. But make sure you specify “application/json”.


def ajaxFindSystems = {
  def result = Systems.list()
  render(contentType:'application/json') {
    results {
      result.each{sys->
        system(id:sys.id, name:sys.name)
      }
    }
    resultset (rows:result.size())
  }
}

Tags: grails json


« Tillbaka