我知道我已经有一个类似的帖子,但是我一生都无法弄清楚这两个片段之间有什么不同-因为我只能从第一个示例中获取返回值-但不能从第二个示例中获取这两种方法在示例中返回一个值。更奇怪(或令人沮丧)的是 php 在第二个示例中没有抛出任何错误,它只是呈现一个空白屏幕。我在 XAMMP 上运行,我相信“显示错误”等设置为 true。
第一个示例(完美运行):
<html>
<?php
function myMethod() {
return "testing";
}
?>
<script type="text/javascript">
var val= "<?php echo myMethod(); ?>";
document.write(val);
</script>
</html>
第二个例子:(注意只有“myMethod”函数发生了变化)
<html>
<?php
function myMethod() {
error_reporting(E_ALL);
echo "<h2>Querying...</h2>\n";
/* Get the port for the WWW service. */
$service_port = getservbyname('www', 'tcp');
/* Get the IP address for the target host. */
$address = gethostbyname('www.example.com');
/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
echo "OK.\n";
}
echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
echo "OK.\n";
}
$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';
echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";
echo "Reading response:\n\n";
while ($out = socket_read($socket, 2048)) {
echo $out;
return 'test';
}
echo "Closing socket...";
socket_close($socket);
echo "OK.\n\n";
}
?>
<script type="text/javascript">
var val= "<?php echo myMethod(); ?>";
document.write(val);
</script>
</html>
更新:根据@the system 所说,看起来该变量包含正确的数据,但“document.write”似乎没有正确地将其输出到浏览器视图:
<html>
<script type="text/javascript">
var val= "<h2>Querying...</h2>
OK.
Attempting to connect to '192.0.43.10' on port '80'...OK.
Sending HTTP HEAD request...OK.
Reading response:
HTTP/1.0 302 Found
Location: http://www.iana.org/domains/example/
Server: BigIP
Connection: close
Content-Length: 0
test";
document.write(val);
</script>
</html>