鍍金池/ 問答/數(shù)據(jù)庫  HTML/ 怎么在前端用Ajax獲取后端接口中的數(shù)據(jù),然后我自己處理

怎么在前端用Ajax獲取后端接口中的數(shù)據(jù),然后我自己處理

目錄結(jié)構(gòu):

clipboard.png

后端路由main.js:

/**
 * Created by Administrator on 2018/4/16.
 */

var express = require('express');
var router = express.Router();

var Category = require('../models/Category');
var Content = require('../models/Content');
var data;
/*
 * 處理通用的數(shù)據(jù)
 * */
router.use(function (req, res, next) {
     data = {
        userInfo: req.userInfo,
        categories:[],
    }
    Category.find().then(function (categories) {
        data.categories = categories;
        next();
    });
});


/*
* 首頁
* */
router.get('/', function (req, res, next) {


    data.category = req.query.category ||'';
    data.count = 0;
    data.page = Number(req.query.page || 1);
    data.limit = 5;
    data.pages = 0;

    var where = {};
    if(data.category){
        where.category = data.category
    }


    Content.where(where).count().then(function (count) {

        data.count = count;
        //計(jì)算總頁數(shù)
        data.pages = Math.ceil( data.count /  data.limit);
        //取值不能超過pages
        data.page = Math.min(   data.page,  data.pages);
        //取值不能小于1
        data.page = Math.max(   data.page, 1);

        var skip = ( data.page-1)* data.limit;

        return Content.where(where).find().limit(data.limit).skip(skip).populate(['category','user']).sort({
            addTime: -1
        });

    }).then(function (contents) {
        data.contents =contents;
        res.render('main/index',data);
    })

});

/*
* 內(nèi)容頁
* */
router.get('/view', function (req, res) {
    
    var contentId = req.query.contentid || '';
    
    Content.findOne({
        _id: contentId
    }).then(function (content) {
        data.content = content;
        console.log(content);

        content.views++;
        content.save();

        res.render('main/view',data);
    });
})



module.exports = router;

前端獲取數(shù)據(jù)comment.js的代碼

$.ajax({
    url:"/main/view",
    data :{
        contentid: $('#contentId').val(),
    },
    async: true,
    success: function(data) {
       console.log(data);
    }
});

clipboard.png

獲取后端路由的數(shù)據(jù)失敗,我就是想把后端里的數(shù)據(jù)里的content數(shù)據(jù)取出來自己處理,不然取出來的數(shù)據(jù)沒有空格和換行

回答
編輯回答
喜歡你

可以把你得到的content內(nèi)容,直接放在html()里;html()方法可以包含html標(biāo)簽的,語法:$(selector).html(content)

2018年8月2日 19:28