2013-01-16 43 views
0
$.ajax({ 
    type: "GET", 
    url: "wordtyping_sql.php", 
    data: "id=" + id + "&formname=" + formname, 
    success: function(msg){ 
     alert("Data Saved: " + msg); 
    } 
}); 

msg包含從wordtyping_sql.php三條線分別是:

echo "one"; 
echo "two"; 
echo "three"; 

如何分別得到這個數據?

回答

5

你想要做的是讓你的PHP代碼回顯出一些JSON數據。然後,您將可以訪問您希望的任何一個變量。

wordtyping_sql.php -

$data = array(
    'one' => 1, 
    'two' => 2, 
    'three' => 3 
); 
echo json_encode($data); 

現在在你的jQuery,你要指定你的AJAX調用有所回報,一個JSON -

$.ajax({ 
    type: "GET", 
    url: "wordtyping_sql.php", 
    data: "id=" + id + "&formname=" + formname, 
    dataType : 'json', // <------------------ this line was added 
    success: function(response){ 
     alert(response.one); 
     alert(response.two); 
     alert(response.three); 
    } 
}); 

退房的relevant documentation pages for jQuery's AJAX method。具體的dataType參數 -

的dataType - 類型,你希望從 服務器返回的數據...

+0

非常感謝,但是當我添加dataType時發生了一件奇怪的事情:'json',我發現alert()部分不工作,沒有任何東西出來。但如果我評論它,它會再次起作用。你知道原因嗎? – user1969371

+0

好吧,它現在可以工作,我想我沒有工作,我沒有添加json_encode。 – user1969371

+0

但還有一個更重要的問題:爲什麼我無法將reponse.one轉換爲id?請參閱下面的代碼:var id = 80;數據類型:「GET」, url:「wordtyping_sql.php」, data:「id =」+ id +「&formname =」+ formname, dataType:'json',// < ----------------添加了這一行 成功:function(response){ id = response.one; } }); alert(id);爲什麼我會看到與response.one的新值相同的值80 intead? – user1969371

0

返回的數據作爲JSON字符串。 jQuery將解析它並將其轉換爲可以使用的對象。

$.ajax({ 
    type: "GET", 
    url: "wordtyping_sql.php", 
    data: "id=" + id + "&formname=" + formname, 
    dataType: "json", 
    success: function(msg){ 
     alert("Data Saved: " + msg); 
    } 
}); 

wordtyping_sql.php

echo '["one","two","three"]'; 

那麼你successhandler內可以訪問數據作爲味精[0],味精[1]。等等。

+0

爲什麼要手動構建JavaScript數組? 'json_encode()'有什麼問題? – Lix

+0

如果「數組」中包含引號字符的任何元素都會導致語法錯誤... – Lix

+0

這僅僅是一個例子,我實際上並不主張靜態構建這樣的數組。我向他展示了數據返回時的樣子。 –