开发者

Why returned JSON data is in different data format?

开发者 https://www.devze.com 2023-01-08 20:41 出处:网络
In the following two different forms, both server side php script return something like this json_encode($results);

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);
                     }
                       });
                  });
              });


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消