【问题标题】:AJAX Syntax Error on XMLHttpRequest.send()XMLHttpRequest.send() 上的 AJAX 语法错误
【发布时间】:2011-04-05 00:51:48
【问题描述】:

我正在处理an AJAX tutorial。我几乎没有网络经验,所以当出现问题时我有点惊讶,我没有回溯,没有日志,什么都没有。

我拿出 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)

【问题讨论】:

  • 这不是 语法 错误。错误的确切文本是什么?
  • 强烈建议将 jQuery 用于与 AJAX 相关的任务。它简化了十倍的代码,并且更兼容跨浏览器。 api.jquery.com/jQuery.ajax
  • @SLaks:我不认为是这样,但这就是错误所说的。我已添加错误消息。
  • @Dutchie432:jQuery 的下载链接似乎已损坏。

标签: javascript ajax syntax


【解决方案1】:

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

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

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

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

【讨论】:

  • 我发布了getChatText。如您所见,我没有打电话给eval
  • 我尝试在lastMessage 上致电encodeUriComponent。我得到了encodeUriComponent is not defined。我还尝试了encodeUrlComponent,以防i 是错字,但我也得到了encodeUrlComponent is not defined
  • 我给encodeURIComponent添加了一个电话。我没有收到not defined 错误,但它没有解决我原来的语法错误。
  • 原来我调用的 PHP 有语法错误,这是我的请求给出的并被 Firebug 捕获。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-23
  • 2012-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多