2014-09-04 38 views
1

我只有最近纔開始使用ajax,我遇到了一個小問題。 代碼如下:Php stdclass對象返回到ajax

  1. 輸入窗體 - > Value to AJAX。
  2. AJAX將表單值發送給將函數發送到服務器的php函數。
  3. 服務器返回一個包含查詢結果的stdClass對象。
  4. PHP將結果作爲responseText發送回AJAX以顯示在webapp上。

問題:

stdClass的對象是,我現在堅持一個PHP對象,它是不可能改變問題的服務器的輸出格式。

我試過所有可能的數組/對象/變量 - 我可以想到的組合,也嘗試json_encode對象。然而,這個解決方案只返回一組很長的字符串,就像對象的var_dump一樣。我可能會犯錯,對json毫無經驗。

我需要一些關於如何將對象傳遞給AJAX的指導,我可以用JavaScript輸出格式。

AJAX代碼:

function checkSerial(serial) { 

     console.log(serial); 

     if (window.XMLHttpRequest) { 
     // code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
     } else { // code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 

     xmlhttp.onreadystatechange=function() { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) { 
      $responseText=xmlhttp.responseText; 
      console.log($responseText); 
     } 
     } 

     xmlhttp.open("GET","../module/getdevice.php?serial="+serial, true); 
     xmlhttp.send(); 

} 

輸出stdClass的。對於審查的值,感到抱歉。

object(stdClass)#5 (15) { 
    ["censored"]=> 
    string(12) "censored" 
    ["censored"]=> 
    string(29) "censored" 
    ["censored"]=> 
    string(1) "censored" 
    ["censored"]=> 
    string(8) "censored" 
    ["censored"]=> 
    string(7) "censored" 
    ["censored"]=> 
    string(0) "censored" 
    ["censored"]=> 
    string(56) "censored" 
    ["censored"]=> 
    string(47) "censored" 
    ["censored"]=> 
    string(47) "censored" 
    ["censored"]=> 
    string(30) "censored" 
    ["censored"]=> 
    string(14) "censored" 
    ["censored"]=> 
    string(0) "censored" 
    ["censored"]=> 
    string(0) "censored" 
    ["censored"]=> 
    string(0) "censored" 
    ["censored"]=> 

希望這個帖子是不是重複,我已經盡我所能積極尋找解決方案。 提前謝謝!

回答

0

您已經在服務器端有解決方案:json_encode()

要轉換您的長字符串在JavaScript中的對象,你可以使用,你需要分析它:

console.log(JSON.parse($responseText)); 
+1

謝謝你的澄清。知道它立即工作。 – Halycon 2014-09-04 22:36:35