2014-10-29 137 views
0

我正在使用this腳本我在互聯網上發現了一個訪問者Web瀏覽器的詳細信息。將PHP數據傳遞給Ajax響應?

當我通過ajax調用發送請求時,該腳本就會運行。

正如你可以在PHP腳本的底部看到,有一個數組,

return array(
     'userAgent' => $u_agent, 
     'name'  => $bname, 
     'version' => $version, 
     'platform' => $platform, 
     'pattern' => $pattern 
    ); 

$ua=getBrowser(); 
$yourbrowser= 
"Your browser: " . $ua['name'] . " 
" . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent']; 

print_r($yourbrowser); 

我怎麼能在這樣通過每這些變量的回阿賈克斯我可以做到這一點的時尚。

$.ajax({          
url: 'analyze.php',  
data: "active=active", 
success: function(data) 
    { 
    var userAgent = data[1]; 
    var name = data[2]; 
    var version = data[3]; 
    $("#div1").html(userAgent); 
    $("#div2").html(userAgent); 
    $("#div3").html(userAgent); 
    }  
}); 
+0

你明白了什麼,當你'的console.log(數據)'? – 2014-10-29 19:41:31

+0

你可以將它編碼爲JSON數據並返回。 – Crackertastic 2014-10-29 19:44:36

回答

2

你必須陣列作爲JSON編碼物體

echo json_encode($array); 

然後AJAX調用將是這樣的:

$.ajax({          
url: 'analyze.php',  
data: "active=active", 
dataType: "json", 
success: function(data) 
{ 
    var userAgent = data.userAgent; 
    var name = data.name; 
    var version= data.version; 
    .... 
} 
+2

你想'echo json_encode()',而不是'return'。 – 2014-10-29 19:51:20

+0

@RocketHazmat你是對的,我誤解了那個函數調用。 – SLin 2014-10-29 19:53:38

+0

@SLin你的變量$ array,來自哪裏?我是否應該將我發佈在$ array中的解釋頂部的數組存儲在數組中? '$陣列= 陣列( '的userAgent'=> $ u_agent' 等? – ProEvilz 2014-10-29 21:14:27

3

可以呼應數據作爲JSON:

echo json_encode($myArray); 

然後加入dataType:'json'和在javascript通過名稱訪問屬性:

dataType: 'json', 
success: function(data) { 
    var userAgent = data.userAgent; 
    var name = data.name; 
    var version = data.version; 
} 
+1

確保將「dataType:'json''添加到AJAX調用中以使其工作。 – 2014-10-29 19:50:38

0

,而不必PHP腳本返回一個數組,有它呼應這樣的信息:

echo "$u_agent,$bname,$version,$platform,$pattern"; 

然後將其轉換成一個數組:

var dataArray = data.split(','); 

然後你就可以訪問每一個變量,像這樣:

var userAgent = dataArray[1]; 
var name = dataArray[2]; 
var version = dataArray[3]; 
0

在你的PHP文件

header('Content-Type: application/json'); // Set the header type to json at the top of the file. 

echo json_encode($array); // Echo out the array as a json-string. 

在你的Ajax成功功能

function (data) { 
    var foo = data.bar; 
}