2016-04-15 110 views
0

我有以下JavaScript代码。它只是类,它应该从REST WCF客户端接收一些数据。代码引发异常'[specific_method]未定义'

class EmployeesWcfClient { 
      constructor(url) { 
       if (url == null) { 
        url = "http://localhost:35798/MyCompanyService.svc/"; 
       } 
       this.url = url; 
      } 


      doGetRequest(relUrl) { 
       return $.ajax({ 
        type: 'GET', 
        contentType: 'json', 
        dataType: 'json', 
        url: this.url + relUrl, 
        async: false 
       }); 
      } 

      doPostRequest(relUrl, data) { 
       return $.ajax({ 
        type: 'POST', 
        data: JSON.stringify(data), 
        contentType: "application/json; charset=utf-8", 
        dataType: "json", 
        url: this.url + relUrl, 
        async: false 
       }); 
      } 

      getEmployees() { 
       return doGetRequest('Employees'); 
      } 
     } 

我不知道为什么会引发异常:'doGetRequest未定义'。有人可以帮忙吗?

+0

你不能在JS/JQ中创建类。如果您尝试创建类'类EmployeesWcfClient',那么编译器将创建一个具有相同名称的函数 –

回答

0

答案很简单: 在'return this.doGetRequest('Employees');'中使用此运算符。在第一个代码示例中,该操作符缺失。

-1

在doGetRequest里面的ajax里this.url不会引用EmployeesWcfClient.url,相反它会指向ajax选项对象本身。所以在调用ajax请求之前请参考这个。

doGetRequest(relUrl) { 
    var _this = this; 
    return $.ajax({ 
     type: 'GET', 
     contentType: 'json', 
     dataType: 'json', 
     url: _this.url + relUrl, 
     async: false 
    }); 
} 

但我不知道这回AJAX功能究竟会返回你请求的响应,虽然你来了async: false。更好地使用回调或承诺。

+0

如果您是向下投票,请评论原因 –