加载中...

express响应前端ajax请求

后端其实并不需要知道前端发起的请求是不是ajax,后端只需要响应请求即可.
例子:
前端这样写:
$('button').on('click', function(event) {
	event.preventDefault();
	/* Act on the event */
	$.ajax({
		url: '/ajax/test',
		type: 'get',
		dataType: 'json',
		success:function(data){
			$('div').html(data.tips);
		},
		error:function(data){
			alert('error');
		}
	});

});
后端就这么写:
app.get('/ajax/test',function(req,res){
  var ajaxTest={
    tips:"you are not alone"
  };
  res.send(ajaxTest);
});

 

posted @ 2016-10-19 02:28  水车  阅读(4910)  评论(0编辑  收藏  举报