在javascript中从方法传递数据
在javascript中对OOP完全陌生,但我正在尽我所能尝试和阅读 我创建了一个名为Invoices的简单测试javascript类。发票只有两种方法。一种方法触发另一种方法。这部分似乎工作得很好 我的问题在于将数据对象从一种方法转移到另一种方法。我在第一个方法中放了一个警报,(据我所知)这个警报应该显示从第二个方法返回的数据。。。但事实并非如此 任何帮助都将不胜感激。哦我也在使用jquery 这是我的密码在javascript中从方法传递数据,javascript,jquery,oop,Javascript,Jquery,Oop,在javascript中对OOP完全陌生,但我正在尽我所能尝试和阅读 我创建了一个名为Invoices的简单测试javascript类。发票只有两种方法。一种方法触发另一种方法。这部分似乎工作得很好 我的问题在于将数据对象从一种方法转移到另一种方法。我在第一个方法中放了一个警报,(据我所知)这个警报应该显示从第二个方法返回的数据。。。但事实并非如此 任何帮助都将不胜感激。哦我也在使用jquery 这是我的密码 function Invoices() { this.siteURL = "h
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;
}
}
这有两个问题。首先,
$.post
是异步的;您必须采用回调方案或使用$.ajax
使其同步。第二,你可能想这样做:
$.post(this.controllerURL + "load_customers", function(data) {
return data;
});
请注意函数调用的括号中是如何包含闭包的。当您被告知AJAX调用是异步的时,您必须在第2步中实现initAdd:
BeginInitAdd
,它将启动AJAX调用EndInitAdd
这将是AJAX调用的回调,并根据返回的数据执行操作谢谢你的回复。我修正了那个语法错误。post部分实际上正在工作。我可以看到XHR请求和json响应,但是警报仍然是未定义的。@Peter-我不明白为什么你说有json响应,但警报是未定义的。您是如何看待json的?您是否正在提醒json数据?
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)
}
}