instead of using $.getJSON(), maybe use $.ajax() directly?

Something like this:

$.ajax({
  url: 'some/url.php',
  data: 'id=' + $("#id").val(),
  type: 'post',
  dataType: 'json',
  success: function (results) {
    console.log(results);
  }
});

The magic here is the dataType option. It tells $.ajax that it is expecting a JSON object and does what it needs to to convert the results to an object (if possible). The "results" variable is just the object passed to the success callback function - name it whatever makes sense to you. But once inside the success function, you *should* be dealing with an object, not a string.

I find that in most cases $.ajax() is much clearer and causes less grief for me than using the other Ajax type functions (.load(), .getScript(), .getJSON(), .get(), .post(), etc.). I could be wrong, but I think these are all just wrappers to $.ajax() anyways. I do use some of these convenience functions, but the moment I need to start worrying about callbacks, or what data I'm passing, $.ajax() makes life clear and simple for me.

HTH.

Shawn

Alex Weber wrote:
I use $.getJSON for all my ajax stuff and it works beautifully but
there is one particular situation where I use an iframe hack to do an
ajax file upload and even though the returned value is a json object
(created with PHP), jQuery treats it like a string.

I'm using json2.js right now and it does the trick but I don't like
including that much extra code because of one rare situation.

So my question is, be it with $.getJSON or by specifying 'json' as the
expected return type of an ajax request, jQuery *seems* to be able to
convert into json.

The string returned is already a json object, I just need jQuery to be
able to treat it like one.  I've tried wrapping it in a jQuery object
but no use.  (and I really don't want to go down the eval() path)...

Any suggestions?

Thanks!!

Reply via email to