【问题标题】:Pass value in POST Method using JavaScript使用 JavaScript 在 POST 方法中传递值
【发布时间】:2014-07-24 05:16:22
【问题描述】:

这是我的 JavaScript 函数:我通过 google 获得了这个函数。

function postURL() {
    var jobValue = document.getElementsByName('folderName')[0].value;
    url = 'http://localhost:8888/TaaS/Sachin/Input' + "?FolderName=" + jobValue;
    var form = document.createElement("FORM");
    form.method = "POST";
    //if(multipart) {
    form.enctype = "multipart/form-data";
    //}
    form.style.display = "none";
    document.body.appendChild(form);
    form.action = url.replace(/\?(.*)/, function(_, urlArgs) {
        urlArgs.replace(/\+/g, " ").replace(/([^&=]+)=([^&=]*)/g, function(input, key, value) {
            input = document.createElement("INPUT");
            input.type = "hidden";
            input.name = decodeURIComponent(key);
            input.value = decodeURIComponent(value);
            form.appendChild(input);
        });
        return "";
    });
    form.submit();
}

我在onclick期间调用了这个函数;

<button type="submit" class="btn btn-primary start" onclick="postURL()">
    <i class="glyphicon glyphicon-upload"></i>
    <span>Create Folder</span>
</button>

我在服务器端使用 node.js。在服务器端的按钮单击事件期间,正在调用 POST 方法,但我不知道如何在 POST 方法期间检索 node.js 文件中的“jobValue”。

POST方法:

function(req, res) {
    switch (req.method) {
        case 'OPTIONS':
            res.end();
            break;
        case 'POST':
            console.log('req.url: ' + req.url);
            break;
        default:
            res.statusCode = 405;
            res.end();
    }
}

如何在 node.js 文件中获取该值?

【问题讨论】:

  • 放入输入的id,使用document.getElementById('id');
  • 如何在 node.js 文件中获取该值?

标签: javascript node.js http-post


【解决方案1】:

您没有指定,但我假设您在服务器端使用 Express。尽管POST 是一个表单,但您在示例中将jobValue 作为查询字符串参数(FolderName)发送,因此您可以在处理函数中使用:

req.query.FolderName

在您的回调上下文中:

function(req, res) {
    switch (req.method) {
        case 'OPTIONS':
            res.end();
            break;
        case 'POST':
            var jobValue = req.query.FolderName;  //<-- Your variable
            console.log('req.url: ' + req.url);
            break;
        default:
            res.statusCode = 405;
            res.end();
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-08-06
  • 2017-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 2017-10-13
相关资源
最近更新 更多