2013-10-26 61 views
0

按鈕單擊我提交表單並將一些數據發佈到data.php。提交 形式爲: <form action="data.php" method="POST" onsubmit="showUser(this, event)">使用json從ajax請求調用的文件獲取價值

的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

'responseText'是一個字符串!你不能訪問它的屬性。你必須先調用'JSON.parse()'。 – ComFreek

+0

@ComFreek:對於這種情況,我無法獲得任何json示例。你能給我一些提示嗎? – user123

回答

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

希望這有助於..