0

我有两种形式(“表格”和“字段”)。“字段”表单应该通过发出 Ajax 请求,根据“表”中的选择预先填充选项。如果我将一些返回数据的剪切和粘贴示例传递给局部变量(请参阅注释行),则数据将完美返回并且实际上预填充了第二种形式(就像它应该的那样)。但由于某种原因它不会工作返回的对象??任何建议都将不胜感激,因为我对 JavaScript 非常陌生,并且可能遗漏了一些明显的东西!我正在使用以下代码:

$(document).ready(function() {
$('select#table').change(function(){
$.getJSON("/ajax_get",{id: $(this).val(), ajax: 'true'}, function(data) {
//var data = [{"optionValue":"address", "optionDisplay": "address"},{"optionValue":"latitude", "optionDisplay": "latitude"},{"optionValue":"longitude", "optionDisplay": "longitude"},];
  var $persons = $('#fields').empty();
  $.each(data, function() {
    $persons.append("<option value=" + this.optionValue + ">" + this.optionDisplay + "</option>");
  });
});
});
});
4

1 回答 1

0

这是您的通话的简化版本,可以帮助您快速弄清楚:

$.getJSON("/ajax_get",{id: $(this).val(), ajax: 'true'}, function(data) {
  try { 
       typeof(data.somethingYouExpect);
       /* do your on success work here */
  } catch (e) {
     alert('There is a good chance the response was not JSON');
  }
});

即使使用常规的 jQuery$.ajax调用,检查以确保返回的响应是您期望的形式也很重要。这就像success将响应中的变量设置为 true 一样简单。如果你这样做了,上面的例子就会变成这样:

var jqxhr = $.getJSON("/ajax_get",{id: $(this).val(), ajax: 'true'}, function(data) {
  try { 
       typeof(data.success); // Will throw if success is not present
       if (success == true) {
             /* handle success */
       } else {
             /* handle a request that worked, but the server said no */
       }
  } catch (e) {
     /* The actual HTTP request worked, but rubbish was returned */
     alert('There is a good chance the response was not JSON');
     console.dir(jqxhr.textResponse);
  }
});

在这里,我们记住了调用返回的对象$.getJSON(这只是 的快捷方式$.ajax),它允许我们查看服务器发送的实际响应。我敢打赌这是一个 404、解析器错误或类似的东西。

For most things, I usually just use $.ajax mostly out of personal preference, where the error callback passes the xhr object to a common function to examine (did the request return 200? etc). If something explodes, I know exactly what went wrong by briefly looking at the console and can disable debug output in one place.

于 2012-08-03T03:23:33.363 回答