linux - 无法在 bash 中使用/dev/stdin 访问 POSTed 变量

标签 linux bash post cgi

如何在 bash 中访问借助 xmlHttpReq.send 发送的值?

在 perl 中,我可以访问从 html/javascript 文件发送的数据:

#!/usr/bin/perl -w

use CGI;

$query = new CGI;

$secretword = $query->param('w');

print $query->header;
print "<p>The secret word is <b>$secretword</b></p>"

我试图在 sh 脚本中访问“w”,但无法从/dev/stdin 读取。浏览器中不显示任何内容。

#!/bin/sh

echo "Content-type: text/html"
echo ""
echo $(</dev/stdin)

如何在 sh 中访问通过 POST 发送的数据?

这是正在使用的 html/javascript 文件:

<html>
<head>
<title>Ajax Example</title>
<script language="Javascript">
function xmlhttpPost(strURL) {
    var xmlHttpReq = false;
    var self = this;
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText);
        }
    }
    self.xmlHttpReq.send(getquerystring());
}

function getquerystring() {
    var form     = document.forms['f1'];
    var word = form.word.value;
    qstr = 'w=' + escape(word);
    return qstr;
}

function updatepage(str){
    document.getElementById("result").innerHTML = str;
}
</script>
</head>
<body>
<form name="f1">
  <p>word: <input name="word" type="text">  
  <input value="Go" type="button" onclick='JavaScript:xmlhttpPost("./cgi-bin/test_ajax_bash.sh")'></p>
  <div id="result"></div>
</form>
</body>
</html>

最佳答案

使用 read shell 内置命令从标准输入中读取行:

#!/bin/sh

echo "Content-type: text/plain"
echo

while read line; do
  echo $line
done

此外,您不需要 "" 来回显新行。如果您输出纯文本而不是 html,您也可以使用 text/plain mime 类型。

关于linux - 无法在 bash 中使用/dev/stdin 访问 POSTed 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9157179/

相关文章:

c - 过程链接表的用途是什么?

linux - 用外部程序获取命令行上的内容

c++ - Linux SFML - 无法打开共享对象文件

php - 切换 DNS 后 HTTP POST 不起作用

c - 非阻塞 BIO_do_connect 在没有互联网连接时阻塞

bash - 如何将ssh作业发送到后台

linux - bash 中的垃圾收集

linux - Bash 退出状态在脚本中不起作用

Android JSON 发布到 WCF 服务

php - 在 html 中发布带有 javascript 和 php 验证的表单。一个错误 - 返回 true 或 false 进入表单的文本框