weixin_33670713 2016-02-23 18:47 采纳率: 0%
浏览 5

难以获得回应

I'm having some troubles trying to execute an ajax call. It is stored in chat.js (added in the html head) and it does a call to 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');
})()

I checked with alert() and the onreadystatechange event doesn't work.

  • 写回答

1条回答 默认 最新

  • weixin_33712881 2016-02-23 18:52
    关注

    You're not sending the request due to the fact that your .open and .send functions are inside of your callback, try this instead:

    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;
    }
    

    Note, that you are also going to run into issues getting the response to return due to the fact that it's an async request. The response will return undefined unless you either a) make it a synchronous request (generally a bad idea) or b) set your action requiring the response to fire after the ready state has completed. Here is a basic example of how you could do so:

    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>
    
    评论

报告相同问题?