【问题标题】:.ajax error - a is undefined a))();else c.error("Invalid JSON:.ajax 错误 - a 未定义 a))();else c.error("无效 JSON:
【发布时间】:2011-04-27 02:58:57
【问题描述】:

在下面的代码中,为什么会起作用:

var addresses = {"2-avenue-bir-hakiem": "2 Avenue Bir Hakiem", "56-rue-marcel-pagnol": "56 rue Marcel Pagnol"};

但是

var addresses = json.val;

没用

我的 json 输出是有效的!

{"2-avenue-bir-hakiem": "2 Avenue Bir 哈基姆”,“56-rue-marcel-pagnol”:“56 rue Marcel Pagnol"}

我得到的错误是

a 未定义 [中断此错误] a))();else c.error("无效的 JSON: "+a)...f(d)if(i)for(f in a){if(b.apply(a[f],

<script>
$(function() {
    function log( message ) {
        $( "<div/>" ).text( message ).prependTo( "#log" );
        $( "#log" ).attr( "scrollTop", 0 );
    }

    $( "#companies" ).autocomplete({
        source: ";companies",
        minLength: 2,
        select: function( event, ui ) {
            log( ui.item ?
                "Selected: " + ui.item.value + " aka " + ui.item.id :
                "Nothing selected, input was " + this.value );
            $("#address").html(ui.item.id);
            $.ajax({
                type: 'GET',
                url: ';addresses?company=' + ui.item.id,
                dataType: 'json',
                // process the addresses
                success: function(json) {
                    $('body').append('Response Value: ' + json.val);
                    var opts = '';
                    var addresses = {"2-avenue-bir-hakiem": "2 Avenue Bir Hakiem", "56-rue-marcel-pagnol": "56 rue Marcel Pagnol"};
                    //var addresses = json.val;
                    $.each(addresses, function(k, v) {
                        opts += '<option>' + v + '</option>';
                    });
                    $('#address').html(opts);
                }
            }); //end ajax
        } // end select
    });
});
</script>

我错过了什么?

谢谢

【问题讨论】:

  • json,var,是什么样的?也许你不需要 .val 部分?
  • 我认为您实际上并没有收到“无效 JSON”错误。您正在使用缩小的 jQuery,它将很多东西压缩到同一行。使用未缩小的版本(jquery.js 而不是 jquery.min.js),看看哪里出错了。

标签: jquery ajax each


【解决方案1】:
jQuery.parseJSON(response);

$.each 之前试试这个,因为 Jquery 认为你的答案是一个字符串,而不是一个 JSON 对象。

【讨论】:

    【解决方案2】:

    您似乎没有从服务器返回有效的 JSON,而不是 addresses JSON 无效(尽管它只是一个对象字面量)。您确定这是正确的网址吗?

    url: ';addresses?company=' + ui.item.id
    

    检查在 firebug、chrome、fiddler 中返回的响应...您可以使用什么来查看 响应,并在此处检查它是否有效:http://www.jsonlint.com/

    从您的症状看来,您目前收到的回复完全是空的,我认为您使用的 URL 是罪魁祸首,请仔细检查您要获取的内容。

    【讨论】:

      猜你喜欢
      • 2012-12-03
      • 2012-07-24
      • 2014-08-16
      • 1970-01-01
      • 2014-09-24
      • 1970-01-01
      • 1970-01-01
      • 2013-11-11
      • 1970-01-01
      相关资源
      最近更新 更多