2013-10-26 93 views
1

該文件由ajax請求調用。而來到這裏的結果我想在調用函數中放入兩個不同的地方。使用json從ajax請求調用的文件中獲取值

<?php 


//Some processing gives $text 
$s=nl2br($text); 

     $data['x'] = $p; 
     $data['y'] = $q; 

//Start from here 

    echo "<b>Positive count : $x with $p % </b>"; echo "</br>"; 
    echo "<b>Negative count : $y with $q % </b>"; echo "</br>"; 
    echo "</br>"; 
    echo "Page content : "; 
    echo "</br>"; 
    echo "</br>"; 
    echo $s; 
//End. This content should be place in <div1>. Want to send this as a json string 

//Start from here 
    echo "First 5 post"; 
    $result = mysqli_query($con,"select post from facebook_posts where p_id > (select MAX(p_id) - 5 from facebook_posts)"); 
    while ($row = $result->fetch_array(MYSQLI_ASSOC)) 
    { 
     echo $row['post']; 
     echo '<br/>'; 
    } 
//End. This content should be placed in <div2> Want to send this as a json string 

如果只有一個變量,然後我們就可以很容易地做到這一點使用:

$resultArray = array("resultOne" => $result1,"resultTwo" => $result2); 
echo json_encode($resultArray); 

在接收端:

document.getElementById("myFirstDiv").innerHTML=xmlhttp.responseText.resultOne; 
document.getElementById("mySecondDiv").innerHTML=xmlhttp.responseText.resultTwo; 

但怎麼以上覆雜的結果可以放置到json變量?

回答

1

你可以在PHP中使用output buffering

ob_start(); 
// Generate content for div 1... 
$div1 = ob_get_clean(); 

ob_start(); 
// Generate content for div 2... 
$div2 = ob_get_clean(); 

$result = array("div1" => $div1, "div2" => $div2); 
echo json_encode($result); 
+0

Awwsome!感謝budyd –

+0

如果我的答案解決了您的問題,您應該考慮[接受它](http://stackoverflow.com/help/accepted-answer)。 ;) 謝謝! – Aletheios