使用ajax将var从js传递给php无效

时间:2016-12-08 04:14:03

标签: javascript php jquery html ajax

我正在用PHP制作计算器网络应用程序。前端使用HTML,CSS和JS。在我的JS文件中,我试图使用ajax将var传递给PHP。这就是我到目前为止所拥有的:

// Get all the keys from document
var keys = document.querySelectorAll('#calc span');
var operators = ['+', '-', 'x', '÷'];
var decimalAdded = false;

// Add onclick event to all the keys and perform operations
for(var i = 0; i < keys.length; i++) {
keys[i].onclick = function(e) {
    // Get the input and button values
    var input = document.querySelector('.screen');
    var inputVal = input.innerHTML;
    var btnVal = this.innerHTML;

    // Now, just append the key values (btnValue) to the input string and finally use javascript's eval function to get the result
    // If clear key is pressed, erase everything
    if(btnVal == 'C' || btnVal == 'AC') {
        input.innerHTML = '';
        decimalAdded = false;
    }

    // If eval key is pressed, calculate and display the result
    else if(btnVal == '=') {
        var equation = inputVal;
        var lastChar = equation[equation.length - 1];

        // Replace all instances of x and ÷ with * and / respectively. This can be done easily using regex and the 'g' tag which will replace all instances of the matched character/substring
        equation = equation.replace(/x/g, '*').replace(/÷/g, '/');
        $.ajax({
            type: "GET",
            url: "calc.php",
            data: {'passVal': equation},
            success: function(data) {

                    alert(data);

            }
        });

我在警报中没有看到任何内容,也没有发布到我指定的php文件中。另一方面,如果我执行以下操作,我会在警报中获取数据,但仍不确定如何传递给php文件:

....rest of code
   $.ajax({
            type: "POST",
            url: "calc.php",
            data: {'passVal': equation},
            success: function(data) {
                    alert(equation);
             }
        });

1 个答案:

答案 0 :(得分:2)

在Javascript中(因为我认为这就是你要找的):

var elementValue = document.querySelector('span').value;
//or var elementValue = document.getElementById('idhere').value;
<span class="on">AC</span>
<span>(</span>
<span>)</span>