Ajax数据不发送,但请求文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ajax数据不发送,但请求文件相关的知识,希望对你有一定的参考价值。

我正在尝试使用带有xhttprequest的ajax构建一个聊天系统。我请求文件,文件响应,但获取数据没有达到它。我尝试发送它们即使有帖子,但仍然,数据没有到达php文件。这是请求文件的函数:

    function refreshChat(){
  if(username != ""){

    var date = new Date();
    var timezone_offset = date.getTimezoneOffset();

    $(".messages-container").empty();

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            $(".messages-container").html(this.responseText);
       }
    };
    xhttp.open("GET", "/chat/ajax_requests/get_messages.php", true);
    xhttp.send("receiver="+username+"&sender="+chat_with+"&limit="+limit+"&timezone_offset_minutes="+timezone_offset);
  }
}

请求的文件包含:

  $receiver = $_GET['receiver'];
  $sender = $_GET['sender'];
  $limit = $_GET['limit'];
  $timezone_offset_minutes  = $_GET['timezone_offset_minutes'];

怎么了?

答案

所以我在w3schools上发现了这个:send(string):将请求发送到服务器。用于POST请求send():将请求发送到服务器。用于GET请求

我建议你将send函数中的字符串添加到url中,如下所示:

xhttp.open("GET", "/chat/ajax_requests/get_messages.php?"+"receiver="+username+"&sender="+chat_with+"&limit="+limit+"&timezone_offset_minutes="+timezone_offset, true);
xhttp.send();

那么你正在使用send函数来获取get请求。

链接到Doc:https://www.w3schools.com/xml/ajax_xmlhttprequest_create.asp

以上是关于Ajax数据不发送,但请求文件的主要内容,如果未能解决你的问题,请参考以下文章

使用 AJAX 提交时发送电子邮件不起作用

ajax发送请求

使用 AJAX + 多部分表单数据 + UTF-8 编码发送文件和文本

Structs接收和处理Ajax发送的数据

Ajax--使用jsonp向非同源服务器请求数据

通过ajax发送php代码不起作用