私はすでに同様の投稿を持っていることを知っていますが、最初の例からのみ戻り値を取得できるため、2つのスニペットの違いを理解することはできません.2番目の例では、両方の方法ではありません例では値を返します。さらに奇妙な (またはイライラする) ことは、php が 2 番目の例でエラーをスローせず、単に空白の画面を表示することです。私は XAMMP で実行していますが、「エラーの表示」などが true に設定されていると思います。
最初の例 (完全に動作します):
<html>
<?php
function myMethod() {
return "testing";
}
?>
<script type="text/javascript">
var val= "<?php echo myMethod(); ?>";
document.write(val);
</script>
</html>
2 番目の例: (「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 システムが言ったことに加えて、変数には正しいデータが含まれているように見えますが、「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>