我的ajax函数返回两个值,当我调用"data"时,它们显示为一个值。
Javascript
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'checkinfo.php',
data: { address: "37.187.139.123", port: "26618" },
dataType: 'html',
async: true,
success: function(data)
{
$("output").html(data);
}
});
});
PHP
<?php
$SERVER_IP = $_REQUEST['address'];
$SERVER_PORT = $_REQUEST['port'];
$QUERY_PORT = $_REQUEST['port'];
$HEADS = "3D";
$show_max = "unlimited";
$SHOW_FAVICON = "on";
$TITLE = "My fancy Serverpage";
$TITLE_BLOCK_ONE = "General Information";
$TITLE_BLOCK_TWO = "Players";
$ping = json_decode(file_get_contents('http://api.minetools.eu/ping/' . $SERVER_IP . '/' . $SERVER_PORT . ''), true);
$query = json_decode(file_get_contents('http://api.minetools.eu/query/' . $SERVER_IP . '/' . $QUERY_PORT . ''), true);
if(empty($ping['error'])) {
$version = $ping['version']['name'];
$online = $ping['players']['online'];
$max = $ping['players']['max'];
$motd = $ping['description'];
$favicon = $ping['favicon'];
}
if(empty($query['error'])) {
$playerlist = $query['Playerlist'];
}
echo $version;
echo $online;
?>
我在"output"元素中得到的输出是"Version 1.80"。其中$Version变量是"Version 1.8",$online变量是"0"。如何将这两个值分开,并将它们分配给两个不同元素,例如output1和output2。
最后,有没有更好的方法可以直接从单个变量中获得值,而不是对所有变量使用echo并将其作为一个"数据"进行收集。
您正在处理一个需要解析的纯文本/html响应。此外,ajax函数只返回一个值。PHP脚本所响应的任何内容都会被转储到ajax响应中。
您应该将dataType
更改为json
,并将值作为json编码的数组返回:
die(json_encode(array(
'version' => $version,
'online' => $online
)));
这可以在javascript中访问为:
data.version
data.online
ProTip:如果你不确定返回了什么,请查看Chrome开发工具(或Firebug或其他工具)的"网络"选项卡。Console.log()可用于将var转储到控制台进行检查,执行以下操作将允许您直接在控制台中操作它:
success: function(response) {
console.log(resp=response);
/* open the console, and you can manipulate the var 'resp' */
}