【问题标题】:Equivalant to raw_input (of python) in PHP?相当于 PHP 中的 raw_input(python 的)?
【发布时间】:2015-08-06 20:48:56
【问题描述】:

我对 PHP 不太熟悉,但我想知道如何在 PHP 中的函数内请求输入?例如,使用 python:

def F(q) :
    a = raw_input(q) // how to do this inside a function with PHP?
    // do something with a
    return something 

print F("how bla bla bla ?")
print F("What bla ?")
print F("When bla bla ?")

我不确定如何在函数中请求输入(每次调用它时),因为我们需要定义一个表单并使用 $_POST['aaa'] 获取值!

我尝试过这样做,但我不知道这是否正确,因为我想要的是在函数内部询问输入(每次调用它时)。

<form action="index.php" method="post">
    Name:  <input type="text" name="answer" /><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>

<?php
function F($q)
{
    echo $q;
    $a = $_POST['answer']; // a = raw_input(q)
    $ret = strcmp($a, 'y') == 0 ? 1 : 0;
    return $ret;
}

echo F("how bla bla bla ?")
echo F("What bla ?")
echo F("When bla bla ?")

【问题讨论】:

  • 我投票决定将此问题作为题外话结束,因为 Stack Overflow 不是代码翻译服务。您应该尝试自己编写代码,然后如果遇到问题,您可以发布您尝试过的内容,并清楚地解释什么是'不工作.
  • @JohnConde 我已经编辑了我的问题以添加我尝试过的内容。
  • 谢谢。关闭投票撤回。 :)\
  • 您收到错误是因为 $_POST 未填充。先检查一下表格是否已经提交。当表单提交时,我认为这会起作用。
  • @chris85 是的,但我希望用户仅在调用函数时输入 a 的值,所以我不认为测试 $_POST['answer'] 是否在功能,才是正道。

标签: php input


【解决方案1】:

您遇到的问题是 PHP 在 html 之前被评估,因为在用户点击提交按钮之前您没有任何东西可以“排除”该函数,它正在解析整个事情并抛出错误$_POST 数组为空,更具体地说,$_POST 中不存在“answer”键。

要解决 $_POST 具有未定义的“答案”索引的问题,只需让它等到 $_POST 数组被提交的表单填充:

假设这个文件是index.php:

<form action="index.php" method="post">
    Name:  <input type="text" name="answer" /><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>

<?php
function F($q)
{
    echo $q;
    $a = $_POST['answer']; // a = raw_input(q)
    $ret = strcmp($a, 'y') == 0 ? 1 : 0;
    return $ret;
}

if(isset($_POST['submit'])){
    F("ha ha ha ?")
}

我不知道 raw_input() 在 python 中的作用,但这将有助于解决您的索引问题,让您回到翻译它的正轨。

编辑

(抱歉耽搁了,花了一点时间才写完) 根据要求,以下是您的流程如何工作的示例:

index.php

<input id="send_request" type="submit" name="submit" value="Submit me!" />
<div id="result"></div>
<script>
var obj_merge = function(a, b, e){
    var c={},d={};
    for(var att in a)c[att]=a[att];
    for(var att in b){if(e&&typeof c[att]==='undefined'){d[att]=b[att];}c[att]=b[att];}
    if(e)c={obj:c,extras:function(){return d;}};
    return c;
};
var serialize_obj = function(data, str){
    if(!str) str = "";
    if(data){
        for(var i in data){
            if(typeof data[i] === 'object') str += serialize_for_post(data[i], str);
            else str += (str.length <= 0) ? i+"="+data[i] : "&"+i+"="+data[i];
        }
    }
    return str;
};
var do_ajax = function(input_config){
    var default_config = {
        url: null,
        req_type: 'GET',
        async: true,
        data: null,
        callback: null
    };
    var config = obj_merge(default_config, input_config);
    if(typeof config.url === 'undefined') return false;

    if(config.data){
        config.data = serialize_obj(config.data);
        if(config.req_type.toUpperCase() === 'GET'){
            config.url = config.url+"?"+config.data
        }
    }

    var xmlhttp;
    if (window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest(); // IE7+, FFx, Chr, Opa, Safi
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //IE5 & IE6
    }
    if("withCredentials" in xmlhttp){
        xmlhttp.open(config.req_type,config.url,config.async);
    } else if(typeof XDomainRequest != "undefined"){
        xmlhttp = new XDomainRequest();
        xmlhttp.open(config.req_type,config.url);
    } else {
        xmlhttp = null;
    }
    if(!xmlhttp){
        console.log("CORS Support Missing.");
        return false;
    }
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState === 4){
            if(typeof config.callback === 'function'){
                config.callback(xmlhttp.responseText, xmlhttp);
            } else {
                console.log(xmlhttp);
            }
        }
    };
    xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    if(config.req_type.toUpperCase() === 'POST'){
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send('POST&'+config.data);
    } else {
        xmlhttp.send();
    }
};

document.getElementById('send_request').onclick = function(event){
    var result = prompt("Enter Something");
    do_ajax({
        url: "ajax_page.php",
        data: {"answer": result},
        req_type: "POST",
        callback: function(response){
            var json_data = JSON.parse(response);
            var output = json_data ? "" : response;
            if(output.length === 0 && json_data){
                for(var key in json_data){
                    output += key+": "+json_data[key]+"<br />";
                }
            }
            document.getElementById('result').innerHTML = output;
        }
    });
};
</script>

ajax_page.php

<?php
function F($a){
    return strcmp($a, 'y') == 0 ? 1 : 0;
}
if(!empty($_POST) && array_key_exists('answer', $_POST)){
    $result = F($_POST['answer']);
    /*
     * DO SOMETHING WITH $result
     */
    echo json_encode(array('status' => true, 'result' => $result));
    die;
} else {
    echo json_encode(array('status' => false, 'error' => 'No answer was provided'));
    die;
}
echo json_encode(array('status' => false, 'error' => 'Something went wrong, sorry about that!'));
die;

【讨论】:

    【解决方案2】:

    您可以使用 php 的命令行版本 (PHP cli getting input from user and then dumping into variable possible?) 执行此操作,否则您需要使用表单提交(或可能是 Ajax)。

    【讨论】:

      【解决方案3】:

      阅读您帖子中的 cmets 后,我认为是:statefull (Python) 和 stateless (PHP)。一个网站从一个请求到另一个请求工作,python 程序开始一次,结束一次。所以你必须在 php 中像在 python 中那样做更多的 kompex 代码逻辑才能完成相同的工作。

      希望对您有所帮助。

      【讨论】:

      • php 不能做他想做的事
      • 标准输入 + 外壳?如果 raw_input() 像 fgets(STDIN) :)
      • 我不明白你的答案,你能举个PHP的例子吗?
      猜你喜欢
      • 2013-04-15
      • 2011-10-10
      • 2010-10-28
      • 1970-01-01
      • 2022-06-12
      • 2011-01-25
      • 1970-01-01
      • 2012-12-03
      • 1970-01-01
      相关资源
      最近更新 更多