简体   繁体   English

我如何将变量发送到 php 文件

[英]how can i send a variable to php file

can someone show me how to send an variable to my php file out of that construct?有人可以告诉我如何从该构造中将变量发送到我的 php 文件吗? i am new at ajax/javascript and i try to figure out my style for writing JS code.我是 ajax/javascript 的新手,我试图找出我编写 JS 代码的风格。 atm i like and understand that kind of version. atm 我喜欢并理解那种版本。

var ajax = new XMLHttpRequest();
var method = "POST"
var url = "data.php" //erweitern - später
var asynchronous = true

var button = document.getElementById("count")
var counter = 0;
button.onclick = function() {
    counter += 2;
    showMoreFood(counter)
};
ajax.open(method, url, asynchronous)
ajax.send()
ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {

        var data = JSON.parse(this.responseText)
        var html =""
        //for (var a = 0; a < data.length; a++) {
        for (var a = 0; a < 2; a++) {
            var firstname = data[a].name
            var preis       = data[a].preis

            html += "<tr>"
            html +=     "<td>" + firstname  + "</td>"
            html +=     "<td>" + preis          + "</td>"
            html += "</tr>"                     
        }
        document.getElementById("data").innerHTML = html
    } // if
} // onready

what i tried:我试过的:

var data = "variable1"
ajax.open(method, url, asynchronous, data)

in data.php
-----------
$variableA = $_POST['variable1'];

because i thought i could send the data within, but nope.因为我以为我可以在其中发送数据,但是不行。 thx and br thx 和 br

i got it.我知道了。 i just need to change that to我只需要把它改成

method = "GET"
url = "data.php?variable1=something"

and in the php file并在php文件中

$variableA = $_GET['variable1'];

and it works :) i dont think thats the right version to handle that but it works :)它有效:) 我不认为那是处理它的正确版本,但它有效:)

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

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