试图使用OOP对象从javascript获取ajax响应

时间:2013-09-20 06:31:03

标签: javascript jquery ajax

所以这是我的代码:

 function CreateDiv(D) {

   D.body = function () {

            var d =
                 $.ajax({
                     type: "GET",
                     url: "Default.aspx",
                     data: 'ExtrFlag=GetChat&userID=1&FriendID=' + this.id,
                     success: function (data) {
                         var StrResponse;
                         StrResponse = data.split('@@@');
                         return StrResponse[0];
                     },
                     error: function (xhr) {
                         return xhr.responseText;
                     }
                 });
            alert(d);

            return "<div class='chatBody' id='chatBody" + this.id + "' >" + d + "</div>";
     };

 }
 function NewChat(id,username,picture) {

        var div = new CreateDiv({ width: 250, height: 285, id: id, username: username, picture: picture });
        div.create();
    }

问题是当执行ajax调用时结果为d=[object object]但在我的情况下它应该是一个字符串,因为ajax服务器端函数总是返回一个字符串。

2 个答案:

答案 0 :(得分:0)

d不是ajax请求的返回值,而是实际的ajax请求处理程序本身。在您的情况下,从服务器返回的值为data

由于ajax根据定义是异步的,因此您无法像在函数中使用它一样使用它。您应该在成功处理程序中处理所有必需的进程,或者您可以返回ajax请求本身的句柄,并使用$.when()$.promise()来处理其他地方的处理

答案 1 :(得分:0)

您无法从异步方法返回值,所有处理ajax请求响应的代码都应添加到ajax请求的成功/失败处理程序中。