Javascript: call a blocking HTTP POST
本问题已经有最佳答案,请猛点这里访问。
我有一个调用函数,它调用另一个函数,该函数用参数发送一个HTTPPOST。现在,我希望这个被称为函数的函数能够阻止执行,直到它"成功"为止(当它的HTTP POST完成时也是如此)。
这是我的逻辑代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | var fingerprint = null; var janus_session = null; var inserted ="false"; $(document).ready(function() { //stuff fingerprint = FindFingerprint(jsep); janus_session = janus.getSessionId(); inserted = SendSDPLine(fingerprint, janus_session); console.log("**in MAIN: inserted=" + inserted); //other stuff } function SendSDPLine(fingerprint, janus_session) { var sdp = fingerprint; // var url ="http://localhost:8484/Shine/AccountController"; var action_type ="InsertSDPLine"; var sessionid = janus_session; $.ajax({ type:"POST", url: url, xhrFields: { withCredentials: false }, data: { "action": action_type, "sdpline": fingerprint, "sessionid": sessionid }, success: function(data) { if (data =="INSERTED") { inserted ="true"; console.log("in SENDSDPLINE: inserted=" + inserted); } return inserted; // return checkFingerprint (fingerprint); }, // vvv---- This is the new bit error: function(jqXHR, textStatus, errorThrown) { console.log("Error, status =" + textStatus +"," + "error thrown:" + errorThrown); } }); } |
简言之,我希望在检查HTTP POST响应之后执行
所以,我有两个问题:
如果需要在Ajax返回之前阻止执行,可以根据jquery文档在Ajax参数中指定
使用回调函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | var fingerprint = null; var janus_session = null; var inserted ="false"; $(document).ready(function() { //stuff fingerprint = FindFingerprint(jsep); janus_session = janus.getSessionId(); //Use callback funcion to access SendSDPLine(fingerprint,janus_session , function(error,inserted){ if(error){ console.log("**Error in :"+error); } console.log("**in MAIN: inserted="+inserted); }); //other stuff } function SendSDPLine(fingerprint,janus_session, callback){ var sdp=fingerprint; // var url ="http://localhost:8484/Shine/AccountController"; var action_type ="InsertSDPLine"; var sessionid = janus_session; $.ajax({ type: "POST", url: url, async: false, xhrFields: { withCredentials: false }, data:{ "action" : action_type, "sdpline" : fingerprint, "sessionid" : sessionid }, success: function(data) { if (data =="INSERTED") { inserted ="true"; console.log("in SENDSDPLINE: inserted="+inserted); //return result return callback(null, inserted); } // return checkFingerprint (fingerprint); }, // vvv---- This is the new bit error: function(jqXHR, textStatus, errorThrown) { console.log("Error, status =" + textStatus +"," + "error thrown:" + errorThrown ); //return error return callback(errorThrown, null); } }); } |