weixin_33734785 2016-12-07 21:50 采纳率: 0%
浏览 29

JavaScript Ajax请求[重复]

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call" dir="ltr">How do I return the response from an asynchronous call?</a>
                            <span class="question-originals-answer-count">
                                (38 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2016-12-07 22:26:48Z" class="relativetime">3 years ago</span>.</div>
        </div>
    </aside>

What I don't understand is when a ajax request, when you call the done function it should be done right? Well I don't get the values until I use a set timeOut then I get my results, why?? I dont get it!!

{"status":"1","msg":"Return Successful","callbackFunct":"LinkMenu.setMenuItems()","return":[{"name":"save","image":"","action":"","status":""},{"name":"back","image":"","action":"","status":""},{"name":"delete","image":"","action":"","status":""}]}

class ServerQuery {

constructor(request, level) {
    console.log("Server query started, " + request + " " + level );
    this.lev = level;
    this.file = "http://" + location.hostname + "/" + this.lev + "/" + request;
    this.values = new Object();
    this.data   = new Array();
    this.result      = null;
    this.setRequiredValues();
}

setRequiredValues() {
    console.log("Setting required Values");
        let ses = document.getElementById("key").value;
        let orgid = document.getElementById("OrgId").value;
        let userid = document.getElementById("userid").value;            
        this.values['key'] = ses;
        this.values['orgid'] = orgid;
        this.values['userid'] = userid;
        console.log("Required Values loaded: " + JSON.stringify(this.values));           
}

addValue(key, insert) {
    console.log("adding Values " + key + " " + JSON.stringify(insert));
    this.r = new Object();
    this.r[key] = insert;
    this.data.push(this.r);
    console.log("Values Added " + JSON.stringify(this.data));              
}

// select this method to trigger a return callback
sendRequest() {
    console.log("Server Query sending Request");
    connect_ajax();

    // this.values is an object
    this.values['linked'] = this.data;
    let req = JSON.stringify(this.values);
    let uandp = "requesting=" + req;
        console.log("Data adding " + uandp);
        $.post(this.file, uandp)
            .done(function done2(result) {
                console.log("server query finsihed with this result " + result);
                this.r = JSON.parse(result);
                if (this.r.status == 1) {
                    console.log("ServerQuery after parse " + this.r);
                    console.log("output " + this.r.callbackFunct);
                    if (typeof this.r.callbackFunct != 'undefined') {
                        setTimeout(function() {
                            this.r.callbackFunct(this.r.callbackVars);
                        }, 500);
                    } else {
                        alert("Callback Not set");
                    }
                }
                else if (this.r.status == 3) {
                    alert(this.r.msg);
                }
            })
            .fail(function processFailed() {
                console.log("an Error has occured");
            })
            .always(function processAlways() {
                console.log("Finished");
            });
        console.log("Requesting url " + this.file);

}   

// select this method to get a static response from server
callRequest() {
    console.log("starting serverquery process() ");
    let answer = this.process();
    console.log("process returned " + answer);
    return answer;

}

process() {
    this.values['linked'] = this.data;
    let req = JSON.stringify(this.values);
    let uandp = "requesting=" + req;
    let file = this.file;
        console.log("Data adding " + uandp);
    let return_first = function () {
    let tmp = null;
    $.ajax({
        'async': false,
        'type': "POST",
        'global': false,
        'dataType': 'html',
        'url': file,
        'data': uandp,
        'success': function (data) {
            tmp = data;
        }
    });
    return tmp;
    }();
    return return_first;
}

cleanUp() {
    delete this.file;
    delete this.values          
    console.log("removed values from global " + this.values);
    console.log("removed file from global " + this.file);
}  
}
</div>
  • 写回答

1条回答 默认 最新

  • weixin_33674437 2016-12-07 22:12
    关注

    The reason why is because a method returns even though you have the asynchronous $.post call still being executed (i.e. it hasn't returned yet). So I believe you are seeing something that you are not expecting.

    If you invoke a function (let's call it ProcessResult) that you passed in, then you can have that ProcessResult function be called once the $.post done is called.

    sendRequest(caller, myDelegateFunction) {
        $.post(this.file, uandp)
                .done(function done2(result) {
                    // this invokes a function and passes in result as a parameter.
                    myDelegateFunction.call(caller, result);
                });
    }
    
    // now you can call this like this:
    function ProcessResult(result) {
       console.log(result);
    }
    sendRequest(this, Hello); // invoke sendRequest function, and pass in 'this' and 'Hello' function.
    
    // or like this:
    sendRequest(this, function(result) {
       console.log(result);
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘