我在尝试执行 ajax 调用时遇到了一些麻烦。它存储在chat.js(添加到html头中),它调用getChatHistory.php
聊天.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";
?>
索引.html:
<script>
(function(){
alert(getChatHistory('user1', 'user2');
})()
我检查了alert()
,onreadystatechange
事件不起作用。
由于 .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
的问题。响应将返回未定义,除非您 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();
}
索引.html
<script>
(function(){
getChatHistory('user1','user2', function(resp){
alert(resp);
});
})();
</script>