【问题标题】:Trying to get this simple Jquery.parseJson to work without success试图让这个简单的 Jquery.parseJson 工作但没有成功
【发布时间】:2010-12-28 16:24:01
【问题描述】:

我试图让这个 Jquery.parseJson 工作但没有成功。

<input type="text" id="query" /><button>search</button><br />
<div id="results">

</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
 $('button').click(function(){
  $("#query").val(); // Do nothing with this value
  $.getJSON('{"name":"John"}',function(json){
   $.each(json.results,function(i,obj){
      $("#results").append('<p>' + obj.name + '</p>');
   });
  });
 });
});
</script>

这段代码的目的是在 div 结果中显示名称“John”。

谁能给我一些关于我做错了什么的线索?

最好的问候,

【问题讨论】:

    标签: jquery json parsing


    【解决方案1】:

    $.getJSON() 用于从 URL 获取 JSON,当您对已有的字符串进行操作时,您只需要 $.parseJSON(),如下所示:

    $('button').click(function(){
      $("#query").val(); // Do nothing with this value
      var obj = $.parseJSON('{"name":"John"}');
      $("#results").append('<p>' + obj.name + '</p>');
    });
    

    【讨论】:

    • 您好,感谢您的回复。但它不起作用。我用过萤火虫,我得到的变量 obj 总是未定义。
    • parseJSON 是在 jQuery 1.4.1 中添加的,他正在使用 1.3.2
    【解决方案2】:

    您可以使用“eval”将字符串转换为 JSON 对象。 请记住,字符串需要用括号括起来才能被识别为带标签的语句。

        <input type="text" id="query" /><button>search</button><br />
        <div id="results">
    
        </div>
    
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $('button').click(function(){
                    $("#query").val(); // Do nothing with this value
                    var json = eval('({"name":"John"})');
                    $("#results").append('<p>' + json.name + '</p>');
                    // $.getJSON('{"name":"John"}',function(json){
                    //     $.each(json.results,function(i,obj){
                    //         $("#results").append('<p>' + obj.name + '</p>');
                    //     });
                    // });
                });
            });
    

    【讨论】:

      【解决方案3】:

      使用 firebug 检查是否传入了 each 语句。

      然后检查json

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-28
        相关资源
        最近更新 更多