点击按钮我提交表单并将一些数据发布到data.php。
提交表格是:
<form action="data.php" method="POST" onsubmit="showUser(this, event)">
的index.php
function showUser(form, e) {
//alert(myid);
e.preventDefault();
e.returnValue=false;
var xmlhttp;
//Get value for sent, text1, text2, text3
console.log(sent);
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(e) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
xmlhttp.responseText.resultOne; // Is this correct? Should be here? I dont know correct
xmlhttp.responseText.resultTwo;
document.getElementById("myFirstDiv").innerHTML=xmlhttp.responseText.resultOne;
document.getElementById("mySecondDiv").innerHTML=xmlhttp.responseText.resultTwo;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
deURIComponent(text3);
xmlhttp.send('sent=' + sent + '&text1=' + text1 + '&text2=' + text2 + '&text3=' + text3);
}
data.php
<?php
ob_start();
echo "1:blah\n";
echo "</br>";
echo "shonice";
echo "1:blahDFDFD\n";
$div1 = ob_get_clean();
ob_start();
echo "2:blah";
echo "</br>";
echo "2:DFDFDFblah\n";
$div2 = ob_get_clean();
$resultArray = array("resultOne" => $div1,"resultTwo" => $div2);
echo json_encode($resultArray);
?>
How can I fetch json value from `data.php` into `myFirstdiv` aand `mysecondDiv`?
我创建的代码有什么问题。 它会在div中显示未定义的值。
答案 0 :(得分:1)
假设data.php文件中有结果,并且它是json编码的..
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var div1=document.getElementById("myFirstDiv");
var div2=document.getElementById("mySecondDiv");
var data=JSON.parse(xmlhttp.responseText);
//alert data to see what u get..
div1.innerHTML=data['resultOne'];
div2.innerHTML=data['resultTwo'];
}
希望这会有所帮助..