简体   繁体   English

PHP制作一个简单的计算器 - 代码不起作用

[英]PHP Make a simple calculator - Code doesnt work

I am trying to make a simple calculator like this : 我想制作一个这样的简单计算器:

input1 select input2 = input3 input1选择input2 = input3

  • input1,input2 is first and second value input1,input2是第一个和第二个值
  • select have 4 operator : + - * / 选择有4个运算符:+ - * /
  • input3 show the result input3显示结果

This is my code and it doesnt work as expected,can someone help me out ? 这是我的代码,它没有按预期工作,有人可以帮助我吗?

<?php
ini_set('display_errors', 0);
session_start();

/*  Check if form is submit 
 *  if any input field is empty --> "NaN" result
 *  else check value of select field --> do the math --> result
 *  Then call JS function to change value of result field
 */ 

if(isset($_GET['act']) && $_GET['act']== 'do')  {

    $val1 = $_GET['val1'];
    $val2 = $_GET['val2'];
    $oper = $_GET['oper'];
if($val1 == NULL || $val2 == NULL)  
    $result= "NaN";
else    {
    switch($oper)   {
        case 1 : $result= $val1 + $val2; break;
        case 2 : $result= $va1l - $val2; break;
        case 3 : $result= $val1 * $val2; break;
        case 4 : $result= $val1 / $val2; break;
    }
}
echo "<script> showResult('".$result."') </script>";
}
?>

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style>
input,select { height:30px;width:50px}

</style>



</head>
<body>
<form method="GET" action="bai4_1.php?act=do">
    <table>
    <tr><td>Op1</td>
        <td>Oper</td>
        <td>Op2</td>
        <td>Result</td></tr>
    <tr><td><input id="val1" type="text" name="val1" value="<?php echo 
$_GET['val1'];?>"/></td>
        <td><select id="oper" name="oper">
            <option value=1>+</option>
            <option value=2>-</option>
            <option value=3>*</option>
            <option value=4>/</option>
            </select></td>
        <td><input id="val2" type="text" name="val2" value="<?php 
echo$_GET['val2'];?>"/> =</td>         
        <td><input id="result" type="text"></td></tr>
    </table>
</form>
</body>
</html>


<script>
$("input,select").change(function(){
setTimeout(function(){
    $("form").submit();
},1000);
});

function showResult(result) {
$("#result").val(result);
}   
</script>

First know what languages you want to use for you application. 首先要知道您想要为您的应用程序使用哪种语言。

I see you use PHP, HTML, JavaScript and jQuery. 我看到你使用PHP,HTML,JavaScript和jQuery。

But if you rethink your small application, you will (maybe) notice that you can do all your actions client side. 但是,如果您重新考虑您的小应用程序,您(可能)会注意到您可以在客户端执行所有操作。 So you could trow away your PHP. 所以你可以扔掉你的PHP。

So now we need HTML to display a form. 所以现在我们需要HTML来显示表单。

<form>
    <table>
        <tr>
            <td>Op1</td>
            <td>Oper</td>
            <td>Op2</td>
            <td>Result</td>
        </tr>
        <tr>
            <td>
                <input id="val1" type="text" name="val1" value="" />
            </td>
            <td>
                <select id="oper" name="oper">
                    <option value="+">+</option>
                    <option value="-">-</option>
                    <option value="*">*</option>
                    <option value="/">/</option>
                </select>
            </td>
            <td>
                <input id="val2" type="text" name="val2" value="" />
            </td>
            <td>
                <input id="result" type="text" />
            </td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td>
                <input type="submit" />
            </td>
        </tr>
    </table>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

In your HTML I edited some things: 在你的HTML中我编辑了一些东西:

  • I added an input type="submit" , we can't assume the user is able to send the form without. 我添加了一个input type="submit" ,我们不能假设用户能够在没有的情况下发送表单。
  • Also I change the values of your select box 我也会更改您选择框的值

Now the form is ready. 现在表格准备好了。

With a little knowledge about jQuery we can easily catch the submit event. 通过对jQuery的一点了解,我们可以轻松捕获提交事件。

$('form').submit(onFormSubmit)

function onFormSubmit() {
    var val1 = $('#val1').val()
    var val2 = $('#val2').val()
    var operator = $('#oper').val()

    $('#result').val(eval(val1 + operator + val2))
    return false
}

Explained above, I have an event listener on the from. 上面解释过,我在from上有一个事件监听器。

After submit I get the 3 values. 提交后我得到3个值。

I use eval to use strings as code, that way I can do eval(val1 + operator + val2) 我使用eval来使用字符串作为代码,这样我就可以做eval(val1 + operator + val2)

I hope this will help you. 我希望这能帮到您。

Include a jsFiddle example here . 在这里包含一个jsFiddle示例

You are probably getting a JavaScript error when you load your page. 加载页面时可能会收到JavaScript错误。 Currently, the source code output of your page probably looks like this: 目前,页面的源代码输出可能如下所示:

<script> showResult('".$result."') </script>
<html>
...
</html>
<script>
...
function showResult(result) {
$("#result").val(result);
}   
</script>

There are two problems here: 这里有两个问题:

You shouldn't have anything, even <script> , outside of your <html> tags. 你的<html>标签之外不应该有任何东西,甚至是<script>

You can move this stuff into the <head> tags so make it look and work nicer. 您可以将这些内容移动到<head>标记中,以使其外观和工作更好。 It's considered bad practice to put things outside of the <html> tags. 把东西放在<html>标签之外被认为是不好的做法。

You are calling your JavaScript function before you define it. 在定义JavaScript函数之前,您正在调用它。

The first JavaScript line tries to execute your ShowResult function. 第一个JavaScript行尝试执行ShowResult函数。 However, this hasn't been defined yet (it's defined at the bottom of the page, and JavaScript hasn't read it yet), so it doesn't know what to do. 但是,这还没有定义(它在页面底部定义,JavaScript还没有读过它),因此它不知道该怎么做。 This causes an error. 这会导致错误。 If you are using Google Chrome or Firefox, then you can view this error message by hitting Control-Shift-J. 如果您使用的是谷歌浏览器或Firefox,则可以通过按Control-Shift-J查看此错误消息。

The Fix 修复

First, move all of your JavaScript code into the <head> of your page. 首先,将所有JavaScript代码移到页面的<head>中。

Second, write your functions first. 其次,先写下你的功能。 This will define them as the page loads, so everything is available once you start executing functions. 这会将它们定义为页面加载,因此一旦开始执行函数,一切都可用。

Third, when you use jQuery, wrap your function execution code (ie: showResult('".$result."') ) in this code: 第三,当你使用jQuery时,在这段代码中包装你的函数执行代码(即: showResult('".$result."') ):

$(document).ready(function() {
    // put your code here
});

This will instruct your code to wait for the entire page to load before starting to execute any JavaScript. 这将指示您的代码在开始执行任何JavaScript之前等待整个页面加载。

The result should look something like this: 结果应如下所示:

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
//  define your functions up here
function showResult(result) {
    $("#result").val(result);
}  

//  define your Procedural code here. This stuff will execute once the page loads completely:
$(document).ready(function() {
    $("input,select").change(function(){
    setTimeout(function(){
        $("form").submit();
    },1000);
    });

    <?php if($result != "NaN") {
    //  Show this code only if $result is defined and valid:
echo "showResult('".$result."');";
?>
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM