2013-04-23 43 views
1

Hy家伙, 我使用jQuery的一些测试,特别是ajax调用。JQuery的Ajax调用与谷歌浏览器,但不是与火狐

$('#jsonpbtn').click(function() { 
     $('#text').html('AJAX Call executing......'); 
     $.ajax({ 
      url : 'http://zip.elevenbasetwo.com/v2/US/10010', 
      type : 'GET', 
      success : function(data) { 
       console.log(data.city); 
       $('#jsonparea').html(data.city); 
       $('#text').html('Ajax Call ended'); 
      }, 
      error : function(xhr, status) { 
       alert(status); 
      }, 

     }); 


    }); 

JSON响应为{城市: “纽约市” 状态: “纽约”,国家: “美国”}

使用Chrome浏览器的一切功能好,其实$('# jsonparea')。html(data.city)在div区域中写入纽约市。与Firefox我有一些问题,其实div区不写,调用alert(data.city)我有未定义的值。

回答

1

将数据类型提供给ajax选项以确保jQuery正确检测数据类型。现在

$('#jsonpbtn').click(function() { 
    $('#text').html('AJAX Call executing......'); 
    $.ajax({ 
     url : 'http://zip.elevenbasetwo.com/v2/US/10010', 
     type : 'GET', 
     dataType: "json", // <---- HERE 
     success : function(data) { 
      console.log(data.city); 
      $('#jsonparea').html(data.city); 
      $('#text').html('Ajax Call ended'); 
     }, 
     error : function(xhr, status) { 
      alert(status); 
     }, 

    }); 

}); 

,如果你的JSON是完全按照你上面贴,你会得到一个parseError,因为它不是有效的JSON,虽然我怀疑它实际上是有效的,因为它在铬工作。

+0

感谢凯文B,你的回答解决了我的问题 – spix 2013-04-23 15:41:39

0

我知道这个'错误'。这是因为如果没有dataType,Firefox不会解析JSON。将ajax调用中的dataType设置为'json'使得该代码对我有用。

你也应该(对IE浏览器),包括从json2.js文件:https://github.com/douglascrockford/JSON-js

var data = typeof data != "object" ? JSON.parse(data) : data; 

考虑到这一点,你会得到:

<html> 
    <head> 
    <script type="text/javascript" src="jquery.js"></script> 
    <script type="text/javascript" src="json2.js"></script> 
    <script> 
    $(function(){ 
    $('#jsonpbtn').click(function() { 
     $('#text').html('AJAX Call executing......'); 
     $.ajax({ 
      url : 'http://zip.elevenbasetwo.com/v2/US/10010', 
      type : 'GET', 
      dataType: "json", // <--- 
      success : function(data) { 
       var data = typeof data != "object" ? JSON.parse(data) : data; // <---- 
       console.log(data.city); 
       $('#jsonparea').html(data.city); 
       $('#text').html('Ajax Call ended'); 
      }, 
      error : function(xhr, status) { 
       alert(status); 
      } 
     }); 
    }); 
    }); 
    </script> 
    </head> 
    <body> 
    <p id="jsonpbtn">click</p> 
    <p id="text"></p> 
    <p id="jsonparea"></p> 
    </body> 
</html> 

此作品在火狐

+0

我试过你的建议,加入和var data = typeof data!=“object”? JSON.parse(data):data;和使用即9,但我得到一个弹出式错误页面sayng只有“错误”。 – spix 2013-04-23 16:16:38

相关问题