更新EJS变量,而无需通过AJAX请求

时间:2018-08-08 05:20:49

标签: javascript node.js ajax express ejs

我当前正在通过AJAX请求更新我的EJS模板,这将从EJS模板返回HTML,该HTML已由服务器每8秒更新一次。然后,我将通过以下方式用新更新的数据替换当前正文:

$("body").html(data);

如何在不替换主体的情况下更新数据,因为这会导致客户端JS出现问题。我只需要ejs中基于变量的数据即可更新整个html等内容。

将GET请求发送至的AJAX请求

app.get('/shopifycall', function(req, res) {
    res.send(jsonOrderCount);
});

app.js

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');

const app = express();

//View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));

// Set Static Path
app.use(express.static(path.join(__dirname, '/public')));

var requestLoop = setInterval(function () {

var request = require("request");

  var options_orders = {
    method: 'GET',
    url: 'https://macwear-clothing-embroidery.myshopify.com/admin/orders.json',
    headers: {
      'Postman-Token': '',
      'Cache-Control': 'no-cache',
      Authorization: ''
    }
  };

  var options_order_count = {
    method: 'GET',
    url: 'https://macwear-clothing-embroidery.myshopify.com/admin/orders/count.json',
    headers: {
      'Postman-Token': '',
      'Cache-Control': 'no-cache',
      Authorization: ''
    }
  };


  request(options_orders, function (error, response, body) {
    if (error) throw new Error(error);
    jsonOrderData = JSON.parse(body);
    console.log(body);
  });

  request(options_order_count, function (error, response, body) {
    if (error) throw new Error(error);
    jsonOrderCount = JSON.parse(body);
    console.log(body);
  });

}, 8000);


app.get('/shopifycall_orders', function (req, res) {
  res.render('dynamic_content');
});

app.get('/', (req, res) => {
  res.render('index');
});

app.listen(3000, () => {
  console.log('Starting MOS2...');
  console.log('Loaded on port 3000');
});

ajax.js

window.onload = function () {
    init();
};


function init() {
// Run AJAX JSON Call
setTimeout(getJSON, 9000);
}

// Shopifycall - AJAX




 function getJSON() {
    $.ajax({
        type: 'GET',
        url: '/shopifycall_orders'
    })
    .done(function(data){
        //console.log('GET Response:', JSON.stringify(data, "", 2));
        //console.log(data);
        $("body").html(data);
        //updateCount(data);
    })
    .fail(function(jqXHR, textStatus, err){
        console.log("AJAX ERROR - Order Data Request", textStatus);             
    });

}

index.ejs

    <div class="infoSection">
        <h1 class="infoTitle" id="count">Current Orders: <%= jsonOrderCount.count %></h1>
        <h1 class="infoTitle">Time: <span id="time"></span></h1>
    </div>
    <div class="sectionMark"></div>
    <div class="orders">
        <div class="filter">
            <div class="orderFilter">
                <span><i class="fas fa-filter"></i></span>
                <span class="custom-dropdown big">
                    <select>
                        <option>Filter Orders</option>
                        <option>Flagged Orders</option>
                        <option>Unsent Needle Sheet</option>
                        <option>Sent Needle Sheet</option>
                        <option>Accepted</option>
                        <option>Rejected</option>
                        <option>Awaiting</option>
                        <option>Past Week</option>
                        <option>Past Month</option>
                    </select>
                </span>
            </div>
        </div>



            <% jsonOrderData.orders.forEach(function(item) { %>

                <div class="order itm<%= item.number %>">
                    <div class="orderDetail">
                        <strong>Order #: <%= item.order_number %></strong>
                    </div>
                    <div class="os"> Order Status: <%= item.financial_status %></div>
                    <div class="ns"> Needle Sheet:
                                            </div>
                    <div class="as"> Acception Status:</div>

                    <div class="btn upload" id="<%= item.number %>">
                        <div class="orderBtns">
                            <i class="fas fa-file-upload"></i>
                        </div>
                    </div>
                    <div class="btn send">
                        <div class="orderBtns">
                            <i class="fas fa-paper-plane"></i>
                        </div>
                    </div>
                    <div class="btn info">
                        <div class="orderBtns">
                            <i class="fas fa-info-circle"></i>
                        </div>
                    </div>
                    <div class="btn flag">
                        <div class="orderBtns">
                            <i class="fas fa-flag"></i>
                        </div>
                    </div>
                    <div class="btn close">
                        <div class="orderBtns">
                            <i class="far fa-times-circle" aria-hidden="true"></i>
                        </div>
                    </div>
                </div>

                <div class="fileUpload up<%= item.number %>" id="m<%= item.number %>">
                    <div class="fileUploadContent">
                        <h2>Customer: <%= item.email %></h2>
                        <div class="uploadFile">
                            <span>Upload File ></span>
                        </div>
                        <div class="optionalMessage">
                            <span>Optional Message:</span>
                            <textarea class="customTextArea"></textarea>
                        </div>
                        <div class="modalOptions">
                            <div class="mButton ok"><span>Ok</span></div>
                            <div class="mButton cancel"><span>Cancel</span></div>
                        </div>
                    </div>
                </div>

            <% }); %>

0 个答案:

没有答案