0

我正在创建一个基本的Php Ajax聊天应用程序。

当我在我自己的 PC 上的跨浏览器中使用这个基本应用程序时(意味着一次 chrome 和 Mozilla 假设两个人)工作正常。但是当我在跨 PC 上使用此应用程序时,意味着一个人正在从一台 PC 聊天,而另一个人正在从第二台 PC 聊天,那么它就无法正常工作..

问题:从一台 PC 发送聊天内容在第二台 PC 上接收,但从第二台 PC(聊天回复)发送聊天内容未接收

 Ajax response is not coming using `set Interval` and browser is not refreshing..

代码 :

J查询

setInterval(function() { 
   $.ajax({
     url: "http://192.168.1.13/naresh/ajaxchat/chatsave.php?q=getChat",
     success: function(response) {
        $("#ulShowChatContent").append(response);
         }
    });
}, 1000);

php

function getChat(){
        $useremail  = $_SESSION['email'];
        $sqlGetUserInfo = mysql_query("select * from  users where email = '$useremail'") or die(mysql_error());
        if(mysql_num_rows($sqlGetUserInfo)>0){
            $userInfo = mysql_fetch_array($sqlGetUserInfo);
            $userId = $userInfo['id']; 
            $currentdate =  date('Y-m-d H:i:s');

            $sqlGetChatContent = mysql_query("select chat_id,chat_content,name from pvt_chat 
                                                INNER JOIN users ON pvt_chat.userid = users.id 
                                                where pvt_chat.userid != '$userId' 
                                                and receive_status = 0
                                                and send_datetime <= '$currentdate' 
                                                ORDER BY send_datetime DESC limit 1") or die(mysql_error());

            if(mysql_num_rows($sqlGetChatContent)>0) {
                $resGetChatContent = mysql_fetch_array($sqlGetChatContent);
                $receiveChatId = $resGetChatContent['chat_id'];
                echo '<li>'.$resGetChatContent['name'].' says : '.$resGetChatContent['chat_content'].'</li>';
                $sqlUpdateRecStatus = mysql_query("UPDATE pvt_chat SET receive_status = '1' WHERE chat_id ='$receiveChatId'") or die(mysql_error());
            }
        }
    }
4

1 回答 1

2

我的问题是:PC2 使用什么网页(+ 域)来访问聊天?如果从他的本地主机或 192.168.1.13 以外的任何域/IP 访问该页面,则您遇到了跨域问题。出于安全原因,今天的浏览器会阻止对另一个域(甚至子域和端口必须是相同的 IIRC)上的网页的 AJAX 调用。如果 PC2 正在从http://localhost/chatPage.html(例如)访问网页,那么他无法在 AJAX 调用中向“http://192.168.1.13”发出请求。

一些解决方案:

  • 将聊天页面托管在与您的 AJAX 调用来源相同的服务器上(以便聊天页面的域与 AJAX 调用的域相同)
  • 使用 JSON 响应并在浏览器中将其转换为 HTML。当您使用 JSON 时,有一种解决跨域问题的方法,但这意味着您必须自己将 JSON 输出转换为 HTML。您还需要确保将属性dataType: 'jsonp'放入 AJAX 调用中。
于 2013-01-02T11:22:38.957 回答