【问题标题】:how can i send html form data to node.js server by making ajax call?如何通过 ajax 调用将 html 表单数据发送到 node.js 服务器?
【发布时间】:2016-01-02 21:50:09
【问题描述】:

我想使用 Ajax 将表单数据发送到 node.js 服务器,我正在采用以下方法来发送数据。

我不知道如何在 node.js 服务器程序中接收它我没有使用 node.js 的 express 框架

client.HTML

<script>
 function myFunction() {
   var region = document.getElementById("region").value;
   var os = document.getElementById("os").value;
   var data = {};
   data.region = region;
   data.os = os;
   $.ajax({
     type: 'post',
     datatype: 'jsonp',
     data: JSON.stringify(data),
     contentType: 'application/json',
     url: 'http://127.0.0.1:8083/', //node.js server is running
     success: function(data) {
       alert("success");

     }
   });

</script>
<form>
<select id="region" name="region" class="region"></select>
<select id="os" name="os" class="os"></select>  
<input type="button" value="search" class="fil_search" onclick="myFunction()"/>
</form>

server.js

var http = require('http');
var fs = require('fs');
var url = require('url');
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert')
var ObjectId = require('mongodb').ObjectID;
var express = require('express');
var bodyParser = require('body-parser');
var app     = express();
var result1=[];
var result2=[];
var result3=[];
var result4=[];
var result5=[];
var result6=[];
var result7=[];
var i=0;
var region;
var os;
app.use(bodyParser.urlencoded({ extended: true })); 

MongoClient.connect("mongodb://192.168.1.22:27017/test", function(err, db) {

if(err) { return console.dir(err); }
else {
app.get('/',function(req, res) {

var url_parts = url.parse(req.url, true);
var url_parsed = url.parse(req.url, true);

"i want data here from ajax to perform"

console.log("connected");


var instance = db.collection('instance');
var region = db.collection('region');

region.findOne(({$and: [{"region_name": region_name},{"os_type": os}]}), function(err, result){
if(err){    
throw(err);
}
else{
console.log(region);
var newr = result.inst_name;

instance.find({ "inst_id": { "$in": newr } }).toArray(function(err, resultn){
if(err){
throw(err);
}
else{       
    var len=resultn.length;

    console.log(resultn);
    console.log(len);

    for(var i=0;i<len;i++)
    {
        result1[i]=resultn[i].inst_type;
        result2[i]=resultn[i].vcpu;
        result3[i]=resultn[i].memory_gib;
        result4[i]=resultn[i].storage;
        result5[i]=resultn[i].phy_processor;
        result6[i]=resultn[i].clock_spd;
        result7[i]=resultn[i].netwk_pef;            
    }
    var wstream = fs.createWriteStream('myOutput.txt');
    wstream.write(result1.toString()+"~"+result2.toString());       
    //var str = "Hi man"
    res.writeHead(200, {'Content-Type':'text/html'});
    //res.end(url_parsed.query.callback+'("'+resultn.toString()+'")'); 
    res.end(url_parsed.query.callback+'("'+result1.toString()+"~"+result2.toString()+"~"
    +result3.toString()+"~"+result4.toString()+"~"+result5.toString()+"~"+result6.toString()
    +"~"+result7.toString()+'")');      
}
});
}
}); 
}).listen(process.env.PORT || 8083);

}
});

我不知道如何在 node.js 服务器程序中接收数据,在接收到数据后,我想处理该数据并将处理后的数据发送回同一 HTML 页面。

【问题讨论】:

  • 这是您的实际代码吗?您在服务器和客户端代码中都有一个语法错误,这将阻止代码运行。你说I am not using express,但是app.use(bodyParser.urlencoded({ extended: true }));看起来像epress,所以你应该告诉你使用哪个框架而不是express。
  • 这是实际代码,但我已将我的代码的 imp 部分粘贴到我想从 HTML 表单发送和接收数据的地方。只是我想要一个解决方案如何在 node.js 服务器中获取数据?
  • 好的,但是'("' + result1.toString()'"); 有语法错误,因此您的服务器代码根本无法运行。而且您在客户端的myFunction 函数末尾缺少},因此此代码也不会运行。而且您仍然没有告诉您使用什么框架而不是 express。如果不是express 应用程序,app 是什么?
  • @t.niese 请再次检查我的程序,我已经上传了完整的工作程序,请给我解决方案。如何在 node.js 服务器中接收数据,我想查询它并再次将数据发送回该 HTML 页面
  • 请有人帮我解决这个问题。提前谢谢

标签: javascript jquery html ajax node.js


【解决方案1】:

如果您的 server.js 文件中有 app.use(bodyParser.urlencoded({ extended: true }));,则使用 bodyParser 您可以从 ajax 检索数据,如下所示:

app.post('/', function(req, res) { //your ajax should also post to url: '/'
    var region = req.body.region,
    os = req.body.os;
    // ...
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 2018-04-17
    • 2013-10-17
    • 2017-01-26
    • 2020-09-03
    相关资源
    最近更新 更多