如何从ajax响应中获取具有不同ID的不同变量值。
在我的程序设计中,从test.php
文件中获取了所有响应,但我想对两个变量进行不同的设置。
Index.php文件:-
<html>
<span> Picture : </span>
<!-- In picture hint i want to print $varbilefirst value from test.php file -->
<span id="picturehintget"></span>
<input type="button" id="<?php echo "8"; ?>" class="submitnone" name="ansclick" onclick="QuestionId(this.id)" value="Submit">
<div> Demo : <p id="demoquiz"></p> </div>
<!--In Demo i want to print $varbilesec value from test.php file -->
<script type="text/javascript">
function QuestionId(obj)
{
var id = obj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("demoquiz").innerHTML = this.responseText;
document.getElementById("picturehintget").innerHTML = this.responseText;
}
};
xhttp.open("GET", "test.php?id=" + id, true);
xhttp.send();
}
</script>
</html>
test.php file
<?php
$id = $_GET['id'];
$varbilefirst = "For Picture Hint";
echo $varbilefirst;
$varbilesec = "For Demo Hint";
echo $varbilesec;
?>
我想要不同的id完全不同的变量值。
<span id="picturehintget">For Picture Hint</span>
<p id="demoquiz">For Demo Hint</p>
答案 0 :(得分:0)
您可以使用数组在php文件中尝试
<?php
$id = $_GET['id'];
$varbilefirst = "For Picture Hint";
$varbilesec = "For Demo Hint";
echo json_encode(["varbilefirst"=>$varbilefirst, "varbilesec"=>$varbilesec]);
?>
使用JavaScript
<script type="text/javascript">
function QuestionId(obj)
{
var id = obj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("demoquiz").innerHTML = this.responseText.varbilesec;
document.getElementById("picturehintget").innerHTML = this.responseText.varbilefirst;
}
};
xhttp.open("GET", "test.php?id=" + id, true);
xhttp.send();
}
</script>
答案 1 :(得分:0)
如果我很了解您的请求,您可以像这样从test.php返回JSON:
<?php
$id = $_GET['id'];
$myObj->demo= $varbilefirst;
$myObj->picture = $varbilesec;
$myJSON = json_encode($myObj);
echo $myJSON;
?>
如果使用Javascript,则在内部:
if (this.readyState == 4 && this.status == 200)
{
var myObj = JSON.parse(this.responseText);
document.getElementById("demoquiz").innerHTML = myObj.demo;
document.getElementById("picturehintget").innerHTML = myObj.picture;
}