为什么 jsonData 未定义,但仅在将其解析为 .text

时间:2021-05-06 17:10:39

标签: jquery

我编写了一个 jQuery 来提交表单,更改一些类并从我的 ASP Classic 页面获取 JSON 响应,这在将 JSON 响应写入控制台时工作正常,并获得正确的值,但是当我将它写入同一个 jQuery 中的 .text 我得到错误返回 Uncaught ReferenceError: jsonData is not defined at HTMLFormElement.<anonymous> 但我不明白为什么它在一个地方有效,而在另一个地方无效。

我的 jQuery:

$(function(){
  $("#FullName<%=objFlowDone("ID")%>").submit(function(){
    $.post($(this).attr("action"), $(this).serialize(), function(jsonData){
      console.log(jsonData.Value1);
    }, "json");

    $('#FullNameColumn<%=objFlowDone("ID")%>').fadeIn("slow").removeClass("HiddenDIV");
        setTimeout(function(){
          $('#FullNameColumn<%=objFlowDone("ID")%>').fadeIn("slow").addClass("HiddenDIV");
          
        }, 10000);

    $('#FullNameText<%=objFlowDone("ID")%>').text(jsonData.Value1);
  });

});

Chrome 开发者工具中的完整错误:

flow.asp?ShowPagePart=FlowDone:1123 Uncaught ReferenceError: jsonData is not defined
    at HTMLFormElement.<anonymous> (flow.asp?ShowPagePart=FlowDone:1123)
    at HTMLFormElement.dispatch (VM44119 jquery.min.js:2)
    at HTMLFormElement.y.handle (VM44119 jquery.min.js:2)
(anonymous) @   flow.asp?ShowPagePart=FlowDone:1123
dispatch    @   jquery.min.js:2
y.handle    @   jquery.min.js:2

1 个答案:

答案 0 :(得分:2)

你需要做任何依赖于异步函数结果的工作在该函数的回调中。

$(function(){
  var id = '<%=objFlowDone("ID")%>';

  $('#FullName' + id).submit(function () {
    $.post($(this).attr("action"), $(this).serialize(), function (jsonData) {
      // this is the callback, do all the work that depends on `jsonData` in here
      $('#FullNameColumn' + id).fadeIn("slow").removeClass("HiddenDIV");
      setTimeout(function () {
        $('#FullNameColumn' +  id).fadeIn("slow").addClass("HiddenDIV");
      }, 10000);
      $('#FullNameText' + id).text(jsonData.Value1);
    }, "json");
  });
});
相关问题