2013-04-17 22 views
0

我有一個腳本我的系統,該系統提供有效的接口列表 -無法PHP字符串傳遞給jQuery的

$ interfaces 
eth0 
lo 
wlan0 

現在這是我的PHP代碼 -

<?php 
$output=shell_exec('./interfaces'); 
$string = trim(preg_replace('/\s+/', ' ', $output)); 
$string = str_replace("\0","",$string); 
$data = preg_split('/\s+/',$string); // There was a typo here, changed $output to 
             // $string 
echo json_encode($data); 
?> 

還有我的jQuery -

$.getJSON('nw/sample1.php', function(data) { 

    $(data).each(function(i,item) { 

      alert(item); 

    }); 

    }); 

我預計應該有3警告框可見活動的每一個突出接口。

對於例如,第一個警告框應該說"eth0",第二說"lo"等,但預期它不是沃金。

我對這一切做了新的事情,所以清楚我在哪裏得到它錯誤?

感謝

編輯:

在瀏覽器

["eth0","lo","wlan0"] 

**每個$(數據,...)和$ data.each sample1.php的輸出... **都表現出相同的方式。

的console.log(數據)輸出 enter image description here

+2

哪部分不按預期工作?你收到了什麼輸出,它是如何不正確的? –

+0

如果您在瀏覽器中訪問該頁面,那麼json_encoded字符串是什麼樣子的? – thaJeztah

+0

你有沒有嘗試'console.log'你的'data'? – fernandosavio

回答

0

我認爲你的問題僅僅是NW/sample1.php

我以前在sample1.php一個「正常」的字符串,而$的getJSON工作就像一個魅力,所以我將重點介紹如何檢索存儲在'interfaces'文件中的數據。只需檢查jQuery JSON是否正在通過將sample1.php中的代碼替換爲:

<?php 
$string = 'eth0 lo wlan0'; 
$string = str_replace("\0","",$string); 
$data = preg_split('/\s+/',$string); 
echo json_encode($data); 
0

添加header('Content-Type: application/json');json_encode($data)之前通知客戶端 - parse it as json instead of text/HTML

所以,

<?php 
$output=shell_exec('./interfaces'); 
$string = trim(preg_replace('/\s+/', ' ', $output)); 
$string = str_replace("\0","",$string); 
$data = preg_split('/\s+/',$string); // There was a typo here, changed $output to 
             // $string 

header('Content-Type: application/json'); // ## ADDED this line ## 
echo json_encode($data); 
?> 

現在,你javascript/jquery應該能夠做 - 你期望它做什麼!

請嘗試恢復!

+0

不......不工作 –