how to use jQuery ajax calls with node.js

前端 未结 4 1413
深忆病人
深忆病人 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:35

    Thanks to yojimbo for his answer. To add to his sample, I wanted to use the jquery method $.getJSON which puts a random callback in the query string so I also wanted to parse that out in the Node.js. I also wanted to pass an object back and use the stringify function.

    This is my Client Side code.

    $.getJSON("http://localhost:8124/dummy?action=dostuff&callback=?",
    function(data){
      alert(data);
    },
    function(jqXHR, textStatus, errorThrown) {
        alert('error ' + textStatus + " " + errorThrown);
    });
    

    This is my Server side Node.js

    var http = require('http');
    var querystring = require('querystring');
    var url = require('url');
    
    http.createServer(function (req, res) {
        //grab the callback from the query string   
        var pquery = querystring.parse(url.parse(req.url).query);   
        var callback = (pquery.callback ? pquery.callback : '');
    
        //we probably want to send an object back in response to the request
        var returnObject = {message: "Hello World!"};
        var returnObjectString = JSON.stringify(returnObject);
    
        //push back the response including the callback shenanigans
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end(callback + '(\'' + returnObjectString + '\')');
    }).listen(8124);
    

提交回复
热议问题