2010-07-23 68 views
0

在以下两种不同的形式中,两个服务器端php脚本都返回 ,像这样json_encode($ results);为什么返回的JSON数据采用不同的数据格式?

所以我假设客户端应该得到JSON数据。

但是,为什么在我的情况下,返回的数据是文本,我们必须先做一些转换,然后才能访问JSON数据。

在情况二中,返回的数据是一个对象,我们可以直接使用。

为什么案例I和案例II不同?

谢谢

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

回答

0

在没有看到数据是如何打包的服务器上,这很难说。我的猜测是尝试在您的Case II $ .ajax()调用中指定一个dataType: 'json'选项。当你这样做会发生什么?如果你没有指定它,jQuery.ajax会猜测返回类型。

+0

你好Hoerster, 你是对的。 添加dataType后,它现在适用于我。 谢谢 – q0987 2010-07-23 21:29:31

+0

很高兴我能帮到你。 – 2010-07-23 23:58:09

相关问题