【问题标题】:passing data from methods in javascript从javascript中的方法传递数据
【发布时间】:2011-01-20 04:46:09
【问题描述】:

对 javascript 中的 OOP 完全陌生,但我尽我所能尝试和阅读。

我创建了一个名为 Invoices 的简单测试 JavaScript 类。发票只有两种方法。一种方法触发另一种方法。这部分似乎工作正常。

我的问题在于将数据对象从一种方法转移到另一种方法。我在第一种方法中放置了一个警报,(据我的理解)这个警报应该显示从第二种方法返回的数据......但它不是。

任何帮助将不胜感激。哦.. 我也在使用 jquery。

这是我的密码。

 function Invoices()
 {
  this.siteURL = "http://example.com/";
  this.controllerURL = "http://example.com/invoices/";
  this.invoiceID = $('input[name="invoiceId"]').val();
 }

 invoice = new Invoices;

 Invoices.prototype.initAdd = function()
 {
  //load customers json obj
  this.customersJSON = invoice.loadCustomers();
  alert(this.customersJSON);

  //create dropdown
 }

 Invoices.prototype.loadCustomers = function ()
 {
  $.post(this.controllerURL + "load_customers"),
  function(data)
  {
   return data;
  }
 }

【问题讨论】:

    标签: javascript jquery oop


    【解决方案1】:

    这样做有两个问题。首先$.post是异步的;您必须采用回调方案或使用$.ajax 使其同步。其次,您可能打算这样做:

    $.post(this.controllerURL + "load_customers", function(data) {
        return data;
    });
    

    注意闭包在函数调用的括号中的位置。

    【讨论】:

    • 感谢您的回复。我修复了那个语法错误。帖子部分实际上正在工作。我可以看到 XHR 请求和 json 响应,但是警报仍然显示未定义。
    • @Peter - 我不明白你为什么说有 json 响应但警报未定义。你是怎么看到 json 的?你在提醒 json 数据吗?
    【解决方案2】:

    正如您被告知 AJAX 调用是异步的,您必须分两步实现您的 initAdd:

    1. BeginInitAdd 将启动 AJAX 调用
    2. EndInitAdd 这将是您的 AJAX 调用的回调,并根据返回的数据执行操作。

    Invoices.prototype.initAdd = function()
    {
        //load customers json obj
        this.xhrObj = invoice.loadCustomers();
        alert(this.customersJSON);
    }
    Invoices.prototype.createDropdown = function (data) {
        //create dropdown
        this.customersJSON=data
    }
    Invoices.prototype.loadCustomers = function ()
    {
        return $.post(this.controllerURL + "load_customers"),
        function(data)
        {
            //return data;
            this.createDropdown(data)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多