作者:新视觉9927 | 来源:互联网 | 2023-02-01 14:51
您好我在jQuery.ajax调用下使用,在我的onBeforeRendering()方法中:
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;
},
为什么console.log(output)
我的onBeforeRendering函数中没有给我定义?我想在我的onBeforeRendering中获取输出结果,以便我可以在渲染之前执行一些验证.在我得到一个解决方法的那一刻,我在收到输出后在onSuccess函数中执行我的验证.但我希望在onBeforeRendering()中调用ajax后执行此操作.但我尝试了console.log(输出)未定义.如何从我的ajax调用的完整属性访问输出?
1> Tomalak..:
几句话
不要用escape()
.此功能已弃用年龄前.它已经破碎了,没有任何理由可以在任何地方使用它.忘了它存在.
如果必须手动转义URL参数,请使用encodeURIComponent()
.
但是,使用jQuery Ajax,您不必手动转义URL参数.使用键和值传递一个对象,jQuery将自己做正确的事情.
当服务器设置时,jQuery还会自动为您解析响应JSON Content-Type: application/json
.
当服务器发送正确的Content-Type标头时,您不需要在请求中指定任何"json"选项,$.get()
而是可以使用而不是更详细的$.ajax()
.
响应数据是成功回调的第一个参数,而不是jqXHR
.
我建议养成使用jQuery基于承诺的Ajax请求接口的习惯.
有了这个,我们可以将您的代码减少为更易读的形式:
onBeforeRendering: function () {
jQuery.get("/prototype/OnlineQuestionnaire/getQuestionsAndResponseChoices.xsjs", {
questionnaireResponseId: questionnaireResponseId
password: password
}).done(function (data) {
console.log(data);
});
}