2017-08-02 22 views
0

我有點失去了,爲什麼我不能得到的數據通過
的JavaScript從PHP數據傳遞到JavaScript的問題json_encode

jQuery.extend({ 
getValues: function(url) { 
    var result = null; 
    $.ajax({ 
    url: url, 
    type: 'get', 
    dataType: 'json', 
    async: false, 
    success: function(data) { 

     result = JSON.stringify(data); 

    } 
return result; 

我與JS部分問題沒有問題,是PHP

$sql = "SELECT name, score FROM scores ORDER BY score DESC LIMIT 10 "; 
$result = mysqli_query($conn1, $sql); 
if (mysqli_num_rows($result) > 0) { 
$data = array(); 
while ($row = mysqli_fetch_assoc($result)) { 
    $data[] = array("name"=>$row['name'], "score"=>$row['score']); 
    $post_data = json_encode(array($data)); 
} 
echo $post_data; 
} 

如果我回聲發表數據裏面的while循環我得到每循環while循環的結果時,回顯發佈數據沒有提供任何內容。如果我print_r數據數組我也得到某種結果。我的問題是我做錯了什麼?
謝謝你的答案我也從確實劣質然而,真正的問題是,名稱中的一個是俄文字母,並從數據庫wasnt UTF-8

回答

0

變化

結果環帶出後數據
result = JSON.stringify(data); 

爲:while循環後

result = JSON.parse(data); 
1

$post_data = json_encode(array($data));,否則就會在每次迭代覆蓋$post_data

while ($row = mysqli_fetch_assoc($result)) { 
    $data[] = array("name"=>$row['name'], "score"=>$row['score']); 
} 
$post_data = json_encode(array($data)); 
echo $post_data; 

我不指望這能解決你的核心問題,但你確實問過「我在做什麼錯」。

讓我們知道你在迴路之後和json_encode()之前用var_export($data);得到了什麼。我們需要看看那些數據結構如何。

+0

@MM你真的想窩你的'$ data'在一個陣列?這就是編碼時發生的情況。這是如果您的查詢正常工作應該發生的事情demostration。 http://sandbox.onlinephpfunctions.com/code/9d820366d2c5bc0bdcfa8b2c3edcc04505b12eca – mickmackusa