使用请求服务器端调用AJAX客户端

时间:2017-02-03 11:41:15

标签: javascript jquery ajax node.js express

我的.ejs文件包含HTMLAJAX。 我想只执行if app.js文件中的条件才是真的。

我使用if调试app.js内的console.log('works')并正常工作。

我的.ejs文件:

<html>
<head>
<script src="jquery-3.1.1.js"></script>
<script src="app.js"></script>

    // .......... etc etc...........
<script>
//function with ajax
function login(usr, pss, numberOrigin){

 $.ajax({
  type: 'POST',
  dataType: "json",
  contentType: "application/json",
  url: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/login',
  data: JSON.stringify({
    "userName":usr,
    "password":pss
    }),
  success:function(output) {
  //  console.log(output.sessionID);
    getData(output.sessionID, numberOrigin);
  },
  error:function(output) {
     }
  });
}
</script>
</body>
</html>

我的app.js文件:
Obs。:在这种情况下,通过updateMessage POST登录API后调用express。我正在集成,而我的if是一个将被操纵的上下文变量,我的app.js识别出这个变量,在这种情况下是response.data(我已经测试过)。

app.post( '/api/xx', function(req, res) {
  var idData= "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxae";  
  if ( !idData|| idData=== '<idData>' ) {
    return res.json( {
      'output': {
        'text': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
      }
    } );
  }
  var payload = {
    idData: idData,
    context: {},
    input: {}
  };
  if ( req.body ) {
    if ( req.body.input ) {
      payload.input = req.body.input;
    }
    if ( req.body.context ) {
      // The client must maintain context/state
      payload.context = req.body.context;
    }
  }
  // Send the input to the service
  api.message( payload, function(err, data) {
    if ( err ) {
      return res.status( err.code || 500 ).json( err );
    }
    updateMessage( res, payload, data );
  } );
} );


function updateMessage(res, input, response) {
  if (response.data!= 'undefined') {
  //console.log('it works');
    login();; //and after getData it's invokes
  }

我的存储库:

Obs。:公用文件夹包含.ejs个文件。

enter image description here

如果我尝试了一些错误,我很抱歉,但如果是的话,请告诉我如何解决这个或另一种解决方法。

感谢提前

0 个答案:

没有答案