2013-12-11 58 views
0

嗨朋友我有一個weired錯誤我使用ajax從其他文件使用php查詢獲取數據它返回一個json_encode,但json.parse有一個問題...... 這裏是我的代碼....Json響應錯誤JSON.parse:意外的數據錯誤結束

,這裏是我的PHP文件.....

switch($_REQUEST['type']){ 
    case 'rec' : 

    $sql=mysql_query("select obs_attendance_punctuality, obs_general_fitness, obs_listening, 
      obs_independence, obs_special_mention, obs_participation, 
      obs_responsibility, obs_awards, obs_nobooks, obs_focused, obs_care_env, obs_projects, 
      obs_hand_control, obs_home_read, obs_workshop_parents, obs_workshop_child, 
      obs_field_trips, obs_homework, obs_eating, obs_batroom, obs_relation, obs_themes, 
      obs_courtesy, obs_instructions, obs_initiative, obs_alertness, obs_descipline, obs_assembly, 
      obs_interest, obs_grade, obs_undergarments, obs_general_hygiene, ".$xtflds." 
      obs_clarity, obs_clarity_rem, obs_tone_pitch, obs_tone_pitch_rem, obs_confidence, 
      obs_confidence_rem, obs_hand_coordination, obs_hand_coordination_rem, obs_eye_coordination, 
      obs_eye_coordination_rem, obs_body_language, obs_body_language_rem, obs_enthusiasm_interest, 
      obs_enthusiasm_interest_rem, obs_facial_expressions, obs_facial_expressions_rem, 
      obs_content, obs_content_rem, obs_vocabulary, obs_vocabulary_rem, obs_body_posture, 
      obs_body_posture_rem, remarks 
      from obsr 
      where obs_code =".$_REQUEST['obs_code']); 

      $data=mysql_fetch_array($sql); 
      echo json_encode($data); 


    return; 
    break; 
     } 

請幫我在這... ......

conso le.log(數據)

被輸出該......

Uncaught SyntaxError: Unexpected end of input 
console.log(data) 
ReferenceError: data is not defined 
message: "data is not defined" 
stack: (...) 
get stack: function() { [native code] } 
set stack: function() { [native code] } 
__proto__: Error 

其不工作.............

+4

我們需要查看php文件輸出的內容,它很可能在某些方面無效。 –

+0

另外,如果不特別將ajax請求的dataType設置爲'text',我會認爲使用'JSON.parse()'是不安全的。最好使用'.getJSON'而不是'JSON.parse()' –

+0

編寫console.log(數據)並檢查控制檯,向我們顯示JSON字符串 – anand4tech

回答

0

在JavaScript中,使用$.getJSON()代替$.get() ...

在PHP中,請務必使用

header('Content-type: application/json'); 

如果你使用它已經,和你的PHP文件不輸出任何東西

echo json_encode($data); 

之前,工作,即使$數據恰好爲空... :-)

+0

我必須定義 header('Content-type:application/json'); – user3091928

+0

您必須在打印任何JSON之前調用它... – MarcoS

+0

我的PHP文件我必須添加此........ – user3091928

0

你必須mysql_fetch_assoc,而不是mysql_fetch_array 。因爲mysql_fetch_array只是返回值的數組而不是鍵值對。

並確保在回顯輸出後沒有打印語句。所以,你必須使用exit()或die()而不是「return」語句。

並確保您的php代碼打印編碼json正確。你可以檢查這個,螢火蟲或鉻開發工具。

+0

mysql_fetch_assoc doesn解決問題.......... – user3091928

+0

@ user3091928,您是否在Chrome開發人員工具中檢查過XHR響應主體?如果是,則發佈該響應主體。 –

+0

這是迴應 未捕獲TypeError:無法讀取null的屬性'obs_attendance_punctuality' – user3091928