how to use jQuery ajax calls with node.js

前端 未结 4 1415
深忆病人
深忆病人 2020-11-30 17:33

This is similar to Stream data with Node.js, but I don\'t feel that question was answered sufficiently.

I\'m trying to use a jQuery ajax call (get, load, getJSON) to

4条回答
  •  误落风尘
    2020-11-30 18:31

    Use something like the following on the server side:

    http.createServer(function (request, response) {
        if (request.headers['x-requested-with'] == 'XMLHttpRequest') {
            // handle async request
            var u = url.parse(request.url, true); //not needed
    
            response.writeHead(200, {'content-type':'text/json'})
            response.end(JSON.stringify(some_array.slice(1, 10))) //send elements 1 to 10
        } else {
            // handle sync request (by server index.html)
            if (request.url == '/') {
                response.writeHead(200, {'content-type': 'text/html'})
                util.pump(fs.createReadStream('index.html'), response)
            } 
            else 
            {
                // 404 error
            }
        }
    }).listen(31337)
    

提交回复
热议问题