XMLHttpRequest.send() 上的 AJAX 语法错误

AJAX Syntax Error on XMLHttpRequest.send()

本文关键字:AJAX 语法 错误 上的 send XMLHttpRequest      更新时间:2023-09-26

我正在学习一个AJAX教程。 我几乎没有网络经验,所以当出现问题时我有点惊讶,我没有回溯,没有日志,什么都没有。

我拔出了Firebug,它说我的两个send()调用都有语法错误。

代码的相关(我认为)部分:

function getChatText() {
    if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
        receiveReq.open("GET", 'getChat.php?chat=1&last=' + lastMessage, true);
        receiveReq.onreadystatechange = handleReceiveChat; 
        receiveReq.send(null);  // <---  Firebug says an error is here
    }           
}
function sendChatText() {
    if (sendReq.readyState == 4 || sendReq.readyState == 0) {
        sendReq.open("POST", 'getChat.php?chat=1&last=' + lastMessage, true);
        sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        sendReq.onreadystatechange = handleSendChat;
        var param = 'message=' + document.getElementById('txt_message').value;
        param += '&name=John Doe';
        param += '&chat=1';
        sendReq.send(param);  // <--- and also here
    }
}

我什至从工作教程中复制/粘贴了这些函数,但我仍然收到相同的错误。 我做错了什么?

确切的错误文本是:

Syntax Error: 
    getChatText()       (line 38)
    handleSendChat()    (line 56)
receiveReq.send(null);  (line 38)

错误发生在getChatText内部(位于错误消息中调用堆栈的顶部)。

您可能使用无效语法调用eval;您可能忘记将 JSON 包装在括号中。

您应该使用 Firebug 的调试器来跟踪错误。

编辑:尝试在lastMessage上拨打encodeURIComponent;这可能会有所帮助。 (无论如何你都应该这样做以防止URL注入)