2010-08-27 127 views

回答

1

使用JSON ENCODE

事情是這樣的:

的index.php

<script type="text/javascript" src="jsfile.js"></script> 

<a href='numbers.php' class='ajax'>Click</a> 

numbers.php

<?php 
    $arr = array ("one" => "1", "two" => "2", "three" => "3"); // your array 
    echo json_encode($arr); // encode it to json 
?> 

個jsfile.js

jQuery(document).ready(function(){ 
    jQuery('.ajax').live('click', function(event) { 
     event.preventDefault(); 
     jQuery.getJSON(this.href, function(snippets) { 
      alert(snippets); // your array in jquery 
     }); 
    }); 
}); 
1

如果它是一個簡單的錯誤消息,並且總是相同的,你可以簡單地返回字符串如「錯誤」並在JavaScript中測試該值。但我建議發送XML格式的complec數據,或者在JSON中發送更好的數據(因爲它比較小,可以在不使用JavaScript的情況下使用)。只是這樣做在你的PHP:

if($error){ 
    echo "error"; 
} else { 
    json_encode($complex_data); 
} 

如果你想要把一些信息到你的錯誤,我強烈建議,只返回使用JSON編碼的錯誤數組。所以用這個替換回聲「錯誤」:

echo json_encode(array("error" => "your error message", "status" => "an optional error status you can compare in JavaScript")) 

比你只需要檢查是否在從PHP返回的JSON中發現「錯誤」。

相關問題