search

Home  >  Q&A  >  body text

node.js - 做一个单页网站,用ajax时,相应的后端用node要怎么写

菜鸟遇到的问题是:pjax改变url,并作相应刷新局部页面。但是如果直接进入到这个url,就会出现问题(页面显示Ajax返回的JSON数据),求大神提供个正确思路

PHPzPHPz2785 days ago618

reply all(3)I'll reply

  • 阿神

    阿神2017-04-17 11:04:17

    My method is to use the Accept header to determine the request type.
    For example, for the same url, /products:
    When requesting, set accept to text/html and the method to get, then an html page will be returned.
    If accept is application/json and the method is get, a product list in json format is returned. /products?limit=20 will return the first 20 items in the list.
    If accept is application/json and the method is put, a product will be added.
    That's probably it, control the result of the request through url, http method, accept,

    Request URL:/products
    Request Method:GET
    
    Request Headers
    Accept:application/json, text/plain, */*
    
    Response Headers
    date:Sun, 24 Nov 2013 07:02:46 GMT
    items-count:3
    page-count:1
    page-number:1
    page-step:20
    Server:BWS/1.0
    vary:Accept-Encoding
    x-powered-by:Express
    

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 11:04:17

    It would be easier if the backend used the express framework.

    res.format({
      'text/html': function() {
        // 这里是直接用 url 访问的 render 逻辑
        // res.render('products', {...});
      },
      'application/json': function() {
        // 这里是 ajax 方式的逻辑
        // res.send({...});
      }
    });
    

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 11:04:17

    Most JavaScript frameworks will include a request header identifying Ajax when sending an Ajax request:

    {"HTTP_X_REQUESTED_WITH" : "XmlHttpRequest"}
    

    If not, you can set one manually, in jQuery it is like this:

    $.ajax {
      beforeSend: function(jqXHR, settings) {
        jqXHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
      }
    };
    

    In this way, the server can make a judgment based on the request header, similar to this:

    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
         /* special ajax here */
         // send JSON data
     } else {
         // send html data
     }
    

    reply
    0
  • Cancelreply