2012-04-02 82 views
5

我想從一個php文件發送多個變量到數組中的json使用ajax。 PHP文件中的代碼完美地工作,並完成與我的數據庫一樣的一切。但是,只要我在ajax中添加dataType:「json」,就不會再發生php文件了。我搜索了一下,有些人提到它可能是瀏覽器問題,但到目前爲止,它在firefox,chrome或IE中都不起作用。我正在使用最新版本的jQuery。dataType:「json」將不起作用

這裏面的PHP發生了什麼:

<?php 
//Create variables and update database 

echo json_encode(array("id" => "$realid", "un" => "$username", "date" => "$date")); 
?> 

這是Ajax代碼:

.ajax(
{ 
    url: 'UpdateComments.php', 
    type: 'POST', 
    dataType: "json", 
    data: 
    { 
     type: "add", 
     comment: $("#comment").val(), 
     id: videoID 
    }, 
    success: function (data) 
    { 
     //Get the data variables from json and display them on page 
    } 
}); 

我在這個毫無章法,任何建議將不勝感激!

+0

檢查的螢火/淨面板Ajax響應,看看什麼是未來從你的服務器。 – 2012-04-02 23:22:50

+0

contentType HTTP頭可能有幫助 – Bergi 2012-04-02 23:24:10

+1

我懷疑返回的內容不是嚴格的JSON - 在PHP之前或之後檢查空格,或者文件中不應該存在的任何其他空格(提示:在json_encode之後使用'die' )。當你沒有在JQuery中指定dataType時,success =獲得響應。當你這樣做時,成功=獲得一個VALID響應....同時檢查你的PHP版本,我似乎記得json_encode在早期版本中被竊聽。 – Codecraft 2012-04-02 23:31:06

回答

6

常見問題是瀏覽器在JSON之前打印「別的東西」,無論這是否可讀或不可讀(不可見)字符。試着做這樣的事情:

<?php 
//at the very beginning start output buffereing 
ob_start(); 

// do your logic here 

// right before outputting the JSON, clear the buffer. 
ob_end_clean(); 

// now print 
echo json_encode(array("id" => $realid, "un" => $username, "date" => $date)); 
?> 

現在,所有的補充數據(JSON)之前將被丟棄,你應該有它的工作...

+0

謝謝,這個伎倆! – Glenn 2012-04-03 00:00:09

0

如果您在jQuery中設置dataType,那實際上會設置Content-Type標頭屬性。也許,在你的PHP腳本中,你需要聲明這個MIME類型爲可接受的。您是否注意到,如果代碼甚至在發出請求時輸入PHP腳本?我懷疑這是瀏覽器問題,如果它不適用於Firefox,Chrome或IE。

爲了在您的AJAX請求中獲得更好的視角,請訂閱ajaxBeforeSend(不知道事件名稱是否正確檢查jQ文檔)事件並記錄xhr對象。

0

我不會使用dataType,如果它導致你的問題,我個人也沒有使用過一個對象作爲數據值之前,也許有什麼關係呢?

無論如何,我已經調整了主要的ajax例程,我希望這有助於。

$.ajax(
{ 
    url: 'UpdateComments.php', 
    type: 'POST', 
    data: 
    { 
     type: "add", 
     comment: $("#comment").val(), 
     id: videoID 
    }, 
    success: function (response) 
    { 
     //Get the data variables from json and display them on page 
     var data = $.parseJSON(response); 
     alert(data.id); 
    } 
}); 
1

我相信如果您使用dataType,應該使用contentType,「JSON的官方Internet媒體類型是application/json」。

.ajax(
{ 
url: 'UpdateComments.php', 
type: 'POST', 
contentType: "application/json",//note the contentType defintion 
dataType: "json", 
data: 
{ 
    type: "add", 
    comment: $("#comment").val(), 
    id: videoID 
}, 
success: function (data) 
{ 
    //Get the data variables from json and display them on page 
} 
}); 
0

嘗試定義錯誤處理程序爲$就調用

$.ajax({ 
    ..., 
    error: function(xml, error) { 
    console.log(error); 
    } 
}); 

然後檢查你的調試控制檯,可以幫助您診斷問題的任何錯誤的一部分。