0

单击按钮时,我提交表单并将一些数据发布到 data.php。需要提交的表格是: <form action="data.php" method="POST" onsubmit="showUser(this, event)">

索引.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);
    }

数据.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 中显示未定义的值。

4

1 回答 1

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'];
                  }

希望这有帮助..

于 2013-10-26T19:27:32.407 回答