tags:

views:

39

answers:

1

Hello all,

In the following two different forms, both server side php script return something like this json_encode($results);

So I assume that the client side should get JSON data.

However, why in case I, the returned data is text and we have to make some conversion before we can access the JSON data.

in case II, the returned data is an object and we can directly use.

Why case I and case II are different?

Thank you

////////////////////////////////////////////////
Case I:
$(document).ready(function() { 

   var options = { 
        success:  processJson,
        dataType: 'json'
    }; 

    // bind form using 'ajaxForm' 
    $('#countyForm').ajaxForm(options); 
});

function processJson(data) {
  // here data is an object
}


//////////////////////////////////////////////////
Case II:
              $(document).ready(function() {
                  $('#the_button').click(function() {
                       $.ajax({
                       type: "GET",
                       url: "chicken_answer.php",
                       data: "first=Sean&last=Rowe",
                       success: function(msg){
                       // msg is not an object, we have to convert it to an object by calling eval
                       jsonObj = eval('(' + msg + ')'); // we're getting back JSON text, so we have to convert it to a JavaScript object.

                       $('#the_answer').html(jsonObj.theAnswer);
                     }
                       });
                  });
              });
A: 

Without seeing how the data is packaged on the server, it's tough to tell. My guess would be to try specifying a dataType: 'json' option in your Case II $.ajax() call. What happens when you do that? If you don't specify it, jQuery.ajax guesses as to the return type.

David Hoerster
Hello Hoerster,You are right.After adding the dataType, it works for me now.Thank you
q0987
Glad I could help.
David Hoerster