2011-05-04 45 views
0

jquery腳本是printng ",爲什麼?用jQuery打印php數組值?

php腳本:

<?php 
session_start(); 

include 'classes/datahandle.class.php'; 

$data = new Datahandle(); 
$query = "SELECT i.instructionValue FROM INSTRUCTION_INPUT i WHERE i.deviceId = '$_SESSION[deviceId]' AND i.instructionState = '1' ORDER BY inputPortNumber"; 
$inputResult = $data->selectDataQuery($query); 

while ($inRow = mysql_fetch_array($inputResult)){ 
    $array[] = $inRow[0]; 
} 

header("Content-type: text/plain"); 
echo json_encode($array); 
?> 

jQuery腳本:

<script> 
$(document).ready(function() { 

    var refreshId = setInterval(function() { 
    $.get('response.php', function(data) { 
     $.each(data, function(index, value) { 
     $('#value'+index).html(value).show(); 
     }); 
    }); 
    }, 3000); 
    $.ajaxSetup({ cache: false}); 
}); 
</script> 

HTML: 

<tbody><tr style="color: white; font-weight: bold;"> 
    </tr> 
     <tr> 
     <td style="text-align: center; color: white; font-weight: bold;" id="value0">[</td> 
    </tr> 
     <tr> 
     <td style="text-align: center; color: white; font-weight: bold;" id="value1">"</td> 
    </tr> 
     <tr> 
     <td style="text-align: center; color: white; font-weight: bold;" id="value2">1</td> 
    </tr> 
     <tr> 
     <td style="text-align: center; color: white; font-weight: bold;" id="value3">1</td> 
    </tr> 
     <tr> 
     <td style="text-align: center; color: white; font-weight: bold;" id="value4">"</td> 
    </tr> 
     <tr> 
     <td style="text-align: center; color: white; font-weight: bold;" id="value5">,</td> 
    </tr> 
     <tr> 
     <td style="text-align: center; color: white; font-weight: bold;" id="value6">"</td> 
    </tr> 
    </tbody> 
+5

你的問題是什麼? – 2011-05-04 15:24:09

+0

爲什麼jQuery不在每個html id中正確地打印來自php數組的值?目前正在印刷「,並且int的凸輪是分開的... – obinoob 2011-05-04 15:27:59

+1

@ FCC-PT:你能明確地表明你得到了什麼,以及你期待什麼嗎? – mellamokb 2011-05-04 15:30:59

回答

2

您需要使用$.getJSON,其解析,而不是試圖處理原始字符串從AJAX請求檢索的JSON對象:

$.getJSON('response.php', function(data) { 

另外,如@Rocket所示,您應該更改header("Content-type: text/plain");header("Content-type: application/json");response.php

以下是不解析JSON的版本,它再現了您的問題:http://jsfiddle.net/XQ7cX/

這裏是解析JSON的版本,它正確顯示:http://jsfiddle.net/XQ7cX/1/

+1

你還應該改變'header(「Content-type:text/plain」);'to header(「Content-type:application/json」);'' – 2011-05-04 15:40:42

+0

解決它是$ .getJSON – obinoob 2011-05-04 15:53:41