jQuery发布错误,并使用2种方法发送对象

时间:2019-02-23 08:58:39

标签: javascript jquery post

我试图在我的javascript中引入OOP,并且尝试使用Jquery $ .post的两个方法发送对象(类)时遇到错误。奇怪的是,当我删除其中一种方法(仅剩下一种)时,我没有错误。

对象定义:

    function Project(project, date) {
    this.id = 0;
    this.project_id = project;
    this.year = date;
    this.percent = 0;
    this.sales = 0;
    this.purchase = 0;
    this.user_update = 'Cubic';
    this.action = '';
}

方法(第一个是引起冲突的方法):

Project.prototype.refreshProject = function () {
    $j("[data-project='" + this.project_id + "'][data-year='" + this.year + "'].pl-sales").text(formatNumber(this.sales));
    $j("[data-project='" + this.project_id + "'][data-year='" + this.year + "'].pl-purchases").text(formatNumber(this.purchase));
    $j("[data-project='" + this.project_id + "'][data-year='" + this.year + "'].pl-margen").text(formatNumber(this.sales - this.purchase));
    calcTotales();
}

Project.prototype.getCorrector = function () {
    corrector = [];
    yearIndex = periods.indexOf(this.year) + 1;
    corrector[0] = stringtoNum($j("[data-rowproject='" + this.project_id + "'].row-sales").text());
    corrector[1] = stringtoNum($j("[data-rowproject='" + this.project_id + "'].row-purchases").text());

    for (var i = yearIndex; i < periods.length; i++) {
        corrector[0] -= stringtoNum($j("[data-project='" + this.project_id + "'][data-year='" + periods[i] + "'].pl-sales").text());
        corrector[1] -= stringtoNum($j("[data-project='" + this.project_id + "'][data-year='" + periods[i] + "'].pl-purchases").text());
    }
    for (var i = yearIndex; i > 1; i--) {
        // modificar year - 1
    }
    return corrector;
}

帖子部分:

recordper = new Project(parseInt($j(this).data('project')), parseInt($j(this).data('year')));
......
$j.post("pl_agency/ajax_request.php",recordper, function (respuesta, status) {
                console.log(respuesta + ' : ' + status);
});
recordper.refreshProject();

错误:调用refreshProject()时,对象(记录器)未定义

感谢您的帮助,请原谅我的英语

1 个答案:

答案 0 :(得分:0)

好的...我找到了一个快捷方式。我不知道是否有更聪明的方法可以这样做,但这对我有用。

我将所有属性(而不是方法)传递给新对象,并将其发送到$ .post

newObj = {
    id : recordper.id,
    project_id : recordper.project_id,
    .......       
};
$j.post("pl_agency/ajax_request.php",newObj, function (respuesta, status) {
...... }

不是很自豪,因为我喜欢最小化代码,但是它可以工作。仍然对更好的解决方案持开放态度。 Tx