2016-02-23 61 views
0

我遇到了一些麻烦,试图执行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事件不起作用。

+0

你是什么意思它不工作?它不是射击?打开你的控制台并检查错误 –

+0

一个问题是你有''hmlhttp.status''而不是'xmlhttp.status'' – Andrew

+0

似乎在index.html中的alert命令中缺少结尾“)”? – Malvolio

回答

2

你不发送请求由于事实,你的。开和功能。发送您是回调里面,试试这个来代替:

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> 
+0

确定的错误。将尝试知道。非常感谢。第一个选项有效,但第二个选项有效......我真的不知道该怎么做。你能举一个例子吗? –

+0

考虑提供一个如何使用'getChatHistory'回调的例子,来说明为什么你不应该返回'response'。虽然答案很好。 – Oka

+0

@Oka我会添加一个简单的例子,谢谢! –