javascript - 从 AJAX 调用的 PHP 脚本,返回值不会一直显示

标签 javascript php jquery ajax sockets

这是我正在做的事情的前提:

I have a program running in the background, a socket server, at all times.

I created a website that calls a php script (using AJAX) that opens a client side socket, connects to the server, sends the request and receives it, then echos it out.

This echo is the response is the 'return value' for my AJAX script.

这是这个问题:

当我点击一个按钮时,信息会发送,但有时,信息永远不会返回到网站。

  • 我知道请求正在通过服务器处理,因为我可以看到请求在服务器端运行完成。
  • 我知道服务器端的信息正在发送到客户端(网站),因为我有一个代码可以检查数据是否已从服务器端成功发送。
  • 有时会发送请求,然后适当的响应客户端(带有来自服务器的信息的警报弹出窗口)会出现。

网站代码:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="submit" class="button" name="weather" value="weather" />
<input type="submit" class="button" name="time" value="time" />
<input type="submit" class="button" name="date" value="date" />
</form>

jQuery 代码:

$(document).ready(function(){
    
$('.button').click(function(){
    var clickBtnValue = $(this).val();
    var ajaxurl = 'php/portserverclient.php',
    dataSend =  {'action': clickBtnValue};
    
    $.post(ajaxurl, dataSend, function (response) {
        // Response div goes here.
        //$('#servermessage').val($('#servermessage').val()+response); 
        alert(response);
    });
});

PHP 代码:

<?php

// -------------------------------------
// ----- Get Information Sent from Site
// -------------------------------------

if (isset($_POST['action']))
    {
         switch ($_POST['action']) {
            case 'weather':
                $in = "3";
                $request = "Weather";
                break;
            case 'time':
                $in = "2";
                $request = "Time";
                break;
            case 'date':
                $in = "1";
                $request = "Date";
        }
    }
else
{
    $in = "3";
    $request = "Weather";
}

// -------------------------------------
// ----- Open Client Side Socket
// -------------------------------------    

error_reporting(E_ALL);

$A1 = "Starting TCP/IP Connection... \n";

/* Get the port for the WWW service. */
$service_port = 51713;

/* Get the IP address for the target host. */
$address = '192.168.8.129';

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
if ($socket === false) 
{
    $A2 = "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
    exit;
} 
else {
    $A2 = "Socket Created...OK.\n";
}
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 5, 'usec' => 0));
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 5, 'usec' => 0));

$A3 = "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) 
{
    $A4 = "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
    exit;
} 
else 
{
    $A4 = "OK.\n";
}

// -------------------------------------
// ----- Send message through socket
// -------------------------------------

$A5 = "Sending $request request...";
$sent = socket_write($socket, $in, strlen($in));
$A6 = "OK.\n";

// -------------------------------------
// ----- Receive response through socket
// -------------------------------------

$out = ' ';
do{$out = socket_read($socket, 20, PHP_NORMAL_READ) ;}
while($out === false);

// -------------------------------------
// ----- Close Client Side Socket
// -------------------------------------

$A7 = "Closing socket...";
$A8 = "OK.\n";
echo "\n From PHP END: ", $A1,$A2,$A3,$A4,$A5,$A6,$A7,$A8,"Message: ", $out,"\n";

socket_shutdown($socket,2);
socket_close($socket);

exit;
?>

C++ 服务器端代码:

//---- read buffer ---
    sizeofread = read(newsockfd, msg, 20);
    if (sizeofread <= 0 || msg[0] == 0x0A || msg[0] == 0x0D || msg[0] == 0x00) 
    {
        // Stops any buggy send (size of read <= 0)
        // Stops terminal from sending new line (0x0A & 0x0D) after each press enter
        // Stops terminal from sending 0 constantly (0x00)
    }
    else
    {
        printf("Received from TCP: %s \n",msg);
         
        //--- Send to Arduino ---
        printf( "Sending to Arduino: %s \n", msg);
        write( uartt, msg, 20 );
        delay(50);  // Here to account for how long it takes to send & receive 20 bytes at 9600 Baud

        //--- Receive from Arduino ---
        while (counter <= 2 && found == false)
        {
            if ( !( msgLength = serialDataAvail(uartt) ))
            {
                printf("Nothing to read \n");
                delay(1071); // Here to account for how long it takes to receive 1024 bytes at 9600 Baud
                counter++;
            }
            else
            {
                found = true;
                read(uartt, msg, msgLength);
                msg[msgLength] = 0;
                if (write(newsockfd, msg, 20) < 0)
                {
                    printf("Failed to send to socket \n");
                }
                else
                {
                    printf("Succesfully sent to socket \n");
                }
                printf("From the Arduino: ");
                printf("%s \n", msg);
            }
            delay(100);
            serialFlush(uartt);
        }
        counter = 0;
        found = false;
        close(newsockfd);
        goto repeat;
    }

最佳答案

原来这个谜语的答案是我需要禁用提交按钮默认事件。通常,在 HTML 中,提交按钮会刷新页面,这必须停止。

它是这样停止的:

$('.button').click(function(event){ 
    var clickBtnValue = $(this).val();
    var ajaxurl = 'php/portserverclient.php',
    dataSend =  {'action': clickBtnValue};

    $.post(ajaxurl, dataSend, function (response) {
        alert(response);
    });

    event.preventDefault();
});

谢谢大家

关于javascript - 从 AJAX 调用的 PHP 脚本,返回值不会一直显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45331109/

相关文章:

java - 将表单输入从 servlet 重定向到另一个表单

php - Laravel DataTables 大导出

php - Mysql_stmt::bind_result()

javascript/jQuery - 在 toggleClass 完成后获取 div 宽度

javascript - 数据表 - 按日期范围过滤 - 不返回正确的结果

javascript - 单击 Tab 时替换窗口

java - 如何为任何网站创建 API?

javascript - ajax POST数据结果在控制台,却显示在页面上?

jquery - WordPress+SmoothDivScroll+Colorbox : Include a permalink for each of the respective image in colorbox

javascript - 将多个输入价格合并为一个 TOTAL