得到回应的问题

时间:2016-02-23 18:47:09

标签: javascript php html ajax

我在尝试执行ajax调用时遇到了一些麻烦。它存储在chat.js中(在html头中添加)并调用getChatHistory.php

chat.js:

function getChatHistory(user1, user2){  
var response = 'fail';
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function()
{
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
        response = response + xmlhttp.responseText;
    } else {
        response = "Error:" + hmlhttp.status;
    }

    xmlhttp.open('GET', 'getChatHistory.php?user1=' + user1 + '&user2=' + user2);
    xmlhttp.send();
}
return response;}

getChatHistory.php:

<?php
echo "the php talks";
?>

的index.html:

<script>
(function(){
  alert(getChatHistory('user1', 'user2');
})()

我使用alert()进行了检查,onreadystatechange事件无效。

1 个答案:

答案 0 :(得分:2)

由于你的.open和.send函数都在你的回调中,你没有发送请求,请尝试这样做:

function getChatHistory(user1, user2){  
    var response = 'fail';
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            response = response + xmlhttp.responseText;
        } else {
            response = "Error:" + hmlhttp.status;
        }
    }

    xmlhttp.open('GET', 'getChatHistory.php?user1=' + user1 + '&user2=' + user2);
    xmlhttp.send();
    return response;
}

请注意,由于它是异步请求,您还将遇到导致response返回的问题。响应将返回undefined,除非你a)使它成为同步请求(通常是一个坏主意)或b)设置你的动作,要求在就绪状态完成后响应。以下是如何执行此操作的基本示例:

function getChatHistory(user1, user2, onComplete){  
    var response = 'fail';
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            response = response + xmlhttp.responseText;
        } else {
            response = "Error:" + hmlhttp.status;
        }

        onComplete(response);
    }

    xmlhttp.open('GET', 'getChatHistory.php?user1=' + user1 + '&user2=' + user2);
    xmlhttp.send();
}

<强>的index.html

<script>
(function(){
  getChatHistory('user1','user2', function(resp){
     alert(resp);
  });
})();
</script>