代码引发异常'未定义[specific_method];

Codes raises exception '[specific_method] is not defined'

本文关键字:specific method 未定义 代码 异常      更新时间:2023-09-26

我有以下javascript代码。它只是一个类,应该从RESTWCF客户端接收一些数据。

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未定义"。有人能帮忙吗?

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

在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。最好使用回调或承诺。