将动态更改div的内容发送到数据库

时间:2017-03-18 16:01:02

标签: javascript php jquery

我有一个服务器发送事件工作和更新网页。然后我将接收SSE的div的内容分配给var,以便将其发送到php文件以插入数据库。 div的数据在sseReceiving.php页面中不断变化,但是如何发送它并且它动态地将值更改为数据库。现在它只是在重新提交页面时将div内容发送到数据库。怎么连续做?

sseTriggering.php

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

//generate random number for demonstration
$new_data = rand(0, 1000);
//echo the new number
//echo "data: New random number:". $new_data. "\n\n";
echo "data:".$new_data."\n\n";;
flush();

sseReceiving.php

<body>
<div id="serverData">Here is where the server sent data will appear</div>   
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
    //create an object, passing it the name and location of the server side script
    var eSource = new EventSource("sseTriggering.php");
    //detect message receipt
    eSource.onmessage = function(event) {
        //write the received data to the page
        document.getElementById("serverData").innerHTML = event.data;
var MyDiv = document.getElementById("serverData").innerHTML;
window.location.href = "findpair.php?pair=" + MyDiv;
};
}
</script>    
</body>

findpair.php

$pair = $_GET['pair'];

$qX = "UPDATE product SET prod_name = '$pair' WHERE id = 1";
$rrr = mysqli_query ($dbc, $qX) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));

我在下面的链接中研究了这个问题,有些人帮我把它带到了现在的舞台。

我还放了标题(&#39;刷新:5&#39;);在php部分的各种文件中没有任何变化。

1 个答案:

答案 0 :(得分:0)

您应该能够通过AJAX为您的主要功能发送请求,这将允许sse事件发送到您的客户端,然后转到您的findpair.php功能。

if(typeof(EventSource)!=="undefined") {
    //create an object, passing it the name and location of the server side script
    var eSource = new EventSource("sseTriggering.php");
    //detect message receipt
    eSource.onmessage = function(event) {
        //write the received data to the page
        document.getElementById("serverData").innerHTML = event.data;

        //Send AJAX request.
        var xmlhttp = new XMLHttpRequest();

        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
                if (xmlhttp.status == 200) {
                    //Do something with 'xmlhttp.responseText' if you want.
                }
                else if (xmlhttp.status == 400) {
                   alert('There was an error 400');
                } else {
                   alert('something else other than 200 was returned');
                }
             }
         };

         xmlhttp.open("GET", "findpair.php?pair=" + event.data, true);
         xmlhttp.send();
    };
}

有关使用javascript提交AJAX请求的更多信息here