2015-10-05 104 views
2

我試圖加載JSON數據與AJAX,但它不起作用。每次ajax調用錯誤函數並且不調用成功函數。加載JSON數據與AJAX和PHP

我的AJAX調用:

$(document).on("click", "#myMovies .btn-update", function() { 
    var id = $(this).parent().data("id"); 

    $.ajax({ 
    url : 'index.php', 
    type : 'POST', 
    dataType: 'json', 
    data : 'id=' + id + '&action=update', 
    success : function(data){ 
     $('#updateMovie') 
      .find('[name="title"]').val(data.title).end() 
      .find('[name="list"]').val(data.list).end(); 
    }, 
    error : function(jqXHR, textStatus, errorThrown){ 
     console.log("error"); 
     alert(textStatus); 
     alert(errorThrown); 
    } 

    }); 
}); 

的index.php的interessing部分:

else if($_POST['action'] == "update") { 
    /*getSpecificMovie($_POST['id']); 
    $movies = getSpecificMovie(); 
    $results = Utils::secureMoviesJSON($movies); 
    echo $results;*/ 

    header("Content-Type: application/json", true); 
    $array = array(
    'title' => 'test', 
    'list' => 'test'); 
    echo json_encode($array, JSON_FORCE_OBJECT); 
} 

任何人都知道是我的錯? 謝謝你的回答。

+1

是否寫 「錯誤」,在控制檯? console.log(「error」,jqXHR,textStatus,errorThrown);在錯誤回調中打印? – lisztomania

+0

不確定,但你可以嘗試用'data:{'id':id','action':'update'}替換'data:'id ='+ id +'&action = update','' –

+0

是的控制檯顯示錯誤然後警報(textStatus)顯示:「parsererror」和警報(errorThrown)顯示:「synthaxError:意外的令牌<」 – onedkr

回答

0

我認爲問題出在'JSON_FORCE_OBJECT'選項。預期的請求的數據類型是一個json字符串。將JSON_FORCE_OBJECT添加到json_encode函數時,json字符串對請求無效。

else if($_POST['action'] == "update") { 
    /*getSpecificMovie($_POST['id']); 
    $movies = getSpecificMovie(); 
    $results = Utils::secureMoviesJSON($movies); 
    echo $results;*/ 

    header("Content-Type: application/json", true); 
    $array = array(
    'title' => 'test', 
    'list' => 'test'); 
    echo json_encode($array); 
    die(); 
} 

還添加了JSON解析器到您的JavaScript(parseJSON):

success : function(data){ 
    data = $.parseJSON(data); 
     $('#updateMovie') 
      .find('[name="title"]').val(data.title).end() 
      .find('[name="list"]').val(data.list).end(); 
    }, 
+0

我已經嘗試過,不幸的是它不工作太:/ – onedkr

+0

你確定PHP腳本打印出來的唯一想法是JSON嗎?也許在回聲後添加一個die()來測試? – sanderbee

+0

是的,我確定這就是爲什麼我找不到解決方案。 add die(); ajax不調用成功或錯誤函數並在控制檯中顯示:「Uncaught SyntaxError:意外的標記o」 – onedkr