show/hide适用于JQuery 1.3.2但不适用于JQuery 1.4

egg*_*ant 2 javascript ajax jquery

我有一个功能,它将数据提交到我的服务器,然后删除编辑UI并将其替换为常规UI.这在JQuery 1.3.2下完美运行,但不适用于JQuery 1.4.0.有任何想法吗?

function save_edit(point_id) {
  var data = {};
  data.id = point_id;
  $.post("/foo", data, function(responseData) {
    $("#value" + point_id).show();
    $("#editval" + point_id).hide();
  }, "json");
}
Run Code Online (Sandbox Code Playgroud)

gna*_*arf 7

jQuery 1.4对于有效的JSON响应文本非常挑剔.以下是无效的JSON(很可能是您的问题)

 {foo:'bar'}

 // Strict JSON requires quoted attributes - and the quotes must be doubles!

 {"foo": "bar"}
Run Code Online (Sandbox Code Playgroud)

如果您无法轻松修复服务器端JSON,则此博客文章提到了使用"文本"的变通方法.应用于您的功能,你得到:

function save_edit(point_id) {
  var data = {};
  data.id = point_id;
  $.post("/foo", data, function(responseText) {
    var responseData = eval("("+responseText+")");
    $("#value" + point_id).show();
    $("#editval" + point_id).hide();
  }, "text");
}
Run Code Online (Sandbox Code Playgroud)

此外,您将能够处理错误情况,执行以下操作:

function save_edit(point_id) {
  var data = {};
  data.id = point_id;
  var $edit = $("#editval"+point_id);
  var $view = $("#value"+point_id);
  $.ajax({
    method: "POST",
    url: "/foo", 
    data: data, 
    success: function(responseData) {
      $view.show();
      $edit.hide().find('.error').remove();
    },
    error: function(XHR, textStatus, errorThrown) {
      var $err = $edit.find(".error");
      if ($err.length == 0) { $err = $("<div class='error'/>").appendTo($edit); }
      $err.text("Error: "+textStatus);
    }
  });
}   
Run Code Online (Sandbox Code Playgroud)