2013-08-17 78 views
2

我在元框中調用ajax調用並返回一些非常簡單的數據。然而,它不斷拋出一個錯誤:WordPress中的ajax/json調用以格式錯誤的JSON結尾

parsererror 
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data 

這裏的Ajax調用:

uid = new Date().getTime(); 
appReq = jQuery.ajax({ 
    type : 'post', 
    dataType : 'json', 
    url : 'admin-ajax.php', 
    data : { action : 'get_app_sidebars', post_id : currentApp, uid : uid } 
}); 
appReq.done(function(data){ 
    if(data.widgetNum > 0 && data.widgetName != '' && data.widgetBase != '') { 
     alert(data); 
    } 
    else { 
     // do something here 
    } 
}); 
appReq.fail(function(jqXHR, textStatus, errorThrown){ 
    alert(textStatus + '\n' + errorThrown); 
}); 

而這裏的PHP:

function get_app_sidebars(){ 
    // get the meta for a custom post type 
    $meta = $this->get_app_meta($_REQUEST['post_id']); 
    $result['widgetNum'] = $meta['num_widgets']; 
    $result['widgetName'] = $meta['widget_name']; 
    $result['widgetBase'] = $meta['widget_base']; 
    $result = json_encode($result); 
    echo $result; 
} 

的問題出現時,我取回數據:

{"widgetNum":"6","widgetName":"Custom Sidebars","widgetBase":"my-custom-sidebars"}0 

好吧,那個當我在螢火蟲中看到這個時,最後的「0」是在迴應中。這讓我瘋狂,我無法弄清楚在發送給瀏覽器的時候,WTF正在使用JSON。如果我修剪0並通過jsonlint運行它,它會通過。我GOOGLE了這一點,只是找不到答案。任何幫助,將不勝感激!

回答

3

我建議使用wp_send_json_success,因爲它需要的一切(JSON編碼,echodie())的護理:

function get_app_sidebars() 
{ 
    $meta = $this->get_app_meta($_REQUEST['post_id']); 
    if($meta) 
    { 
     $result['widgetNum'] = $meta['num_widgets']; 
     $result['widgetName'] = $meta['widget_name']; 
     $result['widgetBase'] = $meta['widget_base']; 
     wp_send_json_success($result); 
    } 
    else 
    } 
     wp_send_json_error(array(
      'error' => 'Custom error message' 
     )); 
    } 
} 

同時,進行必要的安全檢查與check_ajax_referer

+0

非常好,謝謝! –

0

這裏雅去:你需要添加 die(); 迴應結果後。嘖!

0

代碼中的某處顯示0。它不在你提供的函數中,但是這個函數顯然會在某處被調用。您可以通過將echo $result更改爲die($result)來確認此問題,但這不能解決根本問題,即在某處您有不應存在的打印語句。

相關問題