如何在jQuery.ajax()的完整属性中调用的函数中返回?

时间:2017-06-12 10:08:13

标签: jquery ajax sapui5

您好我正在使用jQuery.ajax调用,在我的onBeforeRendering()方法中:

mymodule.directive('modalDialog', function() {
  return {
    restrict: 'E',
    scope: {
      show: '='
    },
    replace: true, 
    transclude: true,
    link: function(scope, element, attrs) {
      scope.dialogStyle = {};
      if (attrs.width)
        scope.dialogStyle.width = attrs.width;
      if (attrs.height)
        scope.dialogStyle.height = attrs.height;
        if (attrs.overflow)
        scope.dialogStyle.overflow = attrs.overflow;
      scope.hideModal = function() {

        scope.show = false;
      };
    },
    template: "<div class='ng-modal' ng-show='show'><div class='ng-modal-overlay' ng-click='hideModal()'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><div class='ng-modal-close' ng-click='hideModal()'><i class='fa fa-times-circle'></i></div><div class='ng-modal-dialog-content' ng-transclude></div></div></div>"// See below
  };
});

为什么我的onBeforeRendering: function() { jQuery.ajax({ url: "/prototype/OnlineQuestionnaire/getQuestionsAndResponseChoices.xsjs?questionnaireResponseId=" + escape( questionnaireResponseId) + "&password=" + escape( password), // url: "/prototype/OnlineQuestionnaire/submitAndCreateQuestionnaire.xsjs", method: "GET", dataType: "json", complete: this.onSuccess, error: this.onErrorCall }); console.log(output); //Gives undefined } onSuccess: function(jqXHR, textStatus) { output = jqXHR.responseText; output = JSON.parse(output); console.log(output) //Gives me my JSON object from my response. return; }, 在我的onBeforeRendering函数中未定义?我想在我的onBeforeRendering中获取输出结果,以便我可以在渲染之前执行一些验证。在我得到一个解决方法的那一刻,我在收到输出后在onSuccess函数中执行我的验证。但我希望在onBeforeRendering()中调用ajax后执行此操作。但我尝试了console.log(输出)未定​​义。如何从我的ajax调用的完整属性访问输出?

1 个答案:

答案 0 :(得分:5)

几句话

  • 不要使用escape()。此功能已被年龄以前弃用。它已经破碎了,没有任何理由可以在任何地方使用它。忘了它存在。
  • 如果您必须手动转义网址参数,请使用encodeURIComponent()
  • 但是,使用jQuery Ajax,您不必手动转义URL参数。使用键和值传递一个对象,jQuery将自己做正确的事。
  • 当服务器设置Content-Type: application/json时,jQuery还会自动解析响应JSON。
  • 当服务器发送正确的Content-Type标头时,您不需要指定任何&#34; json&#34;您的请求中的选项可以使用$.get()代替更详细的$.ajax()
  • 响应数据是成功回调的第一个参数,而不是jqXHR
  • 我建议养成使用jQuery基于承诺的Ajax请求接口的习惯。

有了这个,我们可以将您的代码缩减为更易读的形式:

onBeforeRendering: function () {   
    jQuery.get("/prototype/OnlineQuestionnaire/getQuestionsAndResponseChoices.xsjs", {
        questionnaireResponseId: questionnaireResponseId
        password: password
    }).done(function (data) {
        console.log(data);
    });
}