如何使用javascript在url中传递变量,并使用php接收变量



我要做的是使用url将变量从javascript传递到php文件。假设php将url解析为json字符串,然后将json字符串存储在一个单独的文本文件中。php会将json字符串返回给javascript,以便其显示。经过大量测试,我确实相信我的代码没有打开php文件,或者php没有正确解析url。这是javascript:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
obj = this.responseText;
var data = JSON.parse(obj);
alert(data);
txt += "<tr><th>Student Id</th><th>Student Name</th><th>Type</th></tr>";
for (x in data.student){
txt += "<tr><td>" + data.student[x].id + "</td>";
txt += "<td>" + data.student[x].lname + ", " + data.student[x].fname + "</td>";
txt += "<td>" + data.student[x].type + "</td></tr>";
}
document.getElementById("display").innerHTML = txt;
}

xhttp.open("GET", "assign13.php?type="+type+"&fname="+fname+"&lname="+lname+"&id="+id+"&fname2="+fname2+"&lname2="+lname2+"&id2="+id2, true);
xhttp.send();
alert("all done");
}

这是php文件:

<?php
class student{
public $type;
public $fname;
public $lname;
public $id;
function setAll($type, $fname, $lname, $id){
$this->$fname = $fname;
$this->$type = $type;
$this->$lname = $lname;
$this->$id = $id;
}
}
$s1 = new student();
$s2 = new student();
$type = $_GET["type"];
$fname = $_GET["fname"];
$lname = $_GET["lname"];
$id = $_GET["id"];
$f2 = $_GET["fname2"];
$l2 = $_GET["lname2"];
$i2 = $_GET["id2"];
$s1->setAll($type, $fname, $lname, $id);
$s2->setAll($type, $f2, $l2, $i2);
if ($type == "duet"){
$directory = array($s1, $s2);
}
else{
$directory = array($s1);
}

$str = json_encode($directory);
file_put_contents("../data/data.txt", $str);
echo $str;
?>

您的php类有错误,应该是这样的。。。。。

<?php

class student{
public $type;
public $fname;
public $lname;
public $id;
function setAll($type, $fname, $lname, $id){
$this->fname = $fname;
$this->type = $type;
$this->lname = $lname;
$this->id = $id;
}

function getAll(){
return [
'fname' => $this->fname,
'type' => $this->type,
'lname' => $this->lname,
'id' => $this->id,
];
} 
}
$s1 = new student();
$s2 = new student();
$type = "A";
$fname = "B";
$lname = "C";
$id = "12";
$f2 = "Test";
$l2 = "Test";
$i2 = "10";
$s1->setAll($type, $fname, $lname, $id);
$s2->setAll($type, $f2, $l2, $i2);
if ($type == "duet"){
$directory = array($s1->getAll(), $s2->getAll());
}
else{
$directory = array($s1->getAll());
}

$str = json_encode($directory);
echo $str;
?>

最新更新