简体   繁体   中英

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? i am new at ajax/javascript and i try to figure out my style for writing JS code. atm i like and understand that kind of version.

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

i got it. i just need to change that to

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

and in the php file

$variableA = $_GET['variable1'];

and it works :) i dont think thats the right version to handle that but it works :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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