javascript - jQueries .getJSON 命令上跳过回调函数

标签 javascript jquery callback

我有以下代码片段:

$('input#teamName').live('blur', function() {
  var value = $(this).val();
  if (value) {
    $.getJSON('api/event_company/'+value, function(data) {
      console.log('why does this not want to work?');
    });
  }
});

基本上,它所做的就是在表单字段更改时从服务器请求一些数据。我的问题是,即使我可以使用 firebug 看到它已成功向服务器发送请求并收到有效的 JSON 响应,但回调函数中的任何内容都没有被调用。

如果我将 getJSON 参数更改为:

$.getJSON('api/event_company/'+value, alert('Blah'));

然后警报就会按预期弹出。有什么想法可能导致这种行为吗?

最佳答案

如果 JSON 无效,解析将失败并且不会调用处理程序。来自 getJSON文档:

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.

看看你的 JSON 是否 validates .

你的第二个例子不正确。应该是,

$.getJSON('api/event_company/'+value, function() {
    alert('Blah');
});

关于javascript - jQueries .getJSON 命令上跳过回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3669685/

相关文章:

Javascript音频控制自动播放播放暂停

javascript - Javascript/Jquery 的范围是什么?

Javascript 为什么可以指定不带参数的回调?

javascript - 属性默认值 : attribute. defaultValue

php - 通过 JavaScript 管理网站图像 - 处理这个问题的好方法是什么?

javascript - Kendo UI 颜色选择器不显示选择颜色的对话框

javascript - 停止 Javascript 计时器

jquery - 小数点后最多 2 位尾随数字

javascript - 从字符串数组分配回调事件 (PIXI.js)

javascript - 将变量(从 json 中抓取)插入到元素中