我是一个尝试将代码从原型转换为JQuery的新手。我正在通过基础知识,但我坚持使用下面的代码。我已尝试使用jquery范围,但无法解决它。这是代码,我真的很感激一些帮助。
var SaveForm = Class.create();
SaveForm.prototype = {
formId: null,
responseText: null,
initialize: function(formId)
{
this.formId = formId;
},
sendRequest: function(idform)
{
var referenceThis = this;
$(idform).request(
{
onSuccess: function(transport)
{
referenceThis.responseText = transport.responseText;
referenceThis.onSuccess();
},
onFailure: function(transport)
{
referenceThis.responseText = transport.responseText;
referenceThis.onFailure();
}
});
},
onSuccess: function()
{
},
onFailure: function()
{
}
}
答案 0 :(得分:0)
翻译看起来像这样: - 你不需要使用'Class.create()' - 在创建新的SaveForm实例时,必须使用新的“new” - 将'referenceThis'改为_this。
为什么你传递2次formId?只有一次在初始化中应该足够
var SaveForm = function(){
this.formId;
this.responseText;
};
SaveForm.prototype.initialize = function(formId){
this.formId = formId;
}
SaveForm.prototype.sendRequest = function(idform){
var _this = this;
$(idform).request({
onSuccess: function(transport){
_this.responseText = transport.responseText;
_this.onSuccess();
},
onFailure: function(transport){
_this.responseText = transport.responseText;
_this.onFailure();
}
});
};
SaveForm.prototype.onSuccess = function(){};
SaveForm.prototype.onFailure = function(){};
var form = new SaveForm(); // 'new' is very important!!
form.initialize('myId');
答案 1 :(得分:0)
jQuery适用于DOM,事件处理,Ajax和动画。创建“类”不在其范围内。
但是,您可以轻松地将其转换为简单的JavaScript构造函数和原型方法:
function SaveForm(formId) {
this.formId = formId;
this.responseText = null;
}
SaveForm.prototype.sendRequest = function(idform){
var _this = this;
$(idform).request({
onSuccess: function(transport){
_this.responseText = transport.responseText;
_this.onSuccess();
},
onFailure: function(transport){
_this.responseText = transport.responseText;
_this.onFailure();
}
});
};
SaveForm.prototype.onSuccess = function(){};
SaveForm.prototype.onFailure = function(){};
但是,我不确定您实际需要哪种方法。 jQuery没有request
方法,要做Ajax请求只需使用强大的$.ajax
函数和Defereds功能。听起来像你需要的只是
function submitForm(id) {
var $form = $('#'+id);
return $.ajax({
url: $form.attr("target"),
method: $form.attr("method"),
data: $form.serialize(),
dataType: "html"
});
}
// Usage:
submitForm("myForm")
.done(function onSuccess(responseText) {…})
.fail(function onFailure(error) {…});