簡體   English   中英

是否可以使用jquery ajax更新其他頁面上的元素?

[英]Is it possible to update element on a different page with jquery ajax?

我有一個頁面供用戶提交數據。

/user1.php

$.ajax({
    type: 'POST',
    url:  '/myDB.php',
    data: {
         'val' : val
    },
    dataType : 'json',
    success: function (response) {
         // update user1.php
    }
});

我使用jQuery $.ajax()將數據發布到第二個頁面,在該頁面中將數據存儲到db中,如果成功,則將響應返回給user.php

/myDB.php

$userData = $_POST['userData'];    

// STORE DATA IN DB

echo '{ "status": "Ok" }';

// update user2.php > $('#em').text($userData);

是否可以使用jQuery更新第二個用戶查看的頁面上的另一個元素?

/user2.php 

<div id="em"></div>

我知道我可以從另一個頁面.load()部分內容,只是想知道是否存在反向流動的可能性。

謝謝

最好的方法是檢查是否有任何更改:

checkupdate.php

<?php

// Check database

$res = Array('changed' => false)

if ($data = $res->fetch();){
    $res['changed'] = true;
    $res['data'] = $data;
}

exit(json_encode($res));

在第二頁上:

function checkupdate(){
    $.ajax({
        type: 'POST',
        url:  '/checkupdate.php',
        data: {
             'val' : val
        },
        dataType : 'json',
        success: function (response) {
            if (response.changed){
               // do whatever with reponse.data
            }
        },
        error: function(e){
           // Do whatever when error
           console.log(e);
        },
        complete: function(){
        // Always when finish request do again
        setTimeout(checkupdate, 5);

        }
    });
}

就像Barmar所說的那樣,您可以使用Sockets,但這不是最好的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM