weixin_33692284 2017-01-17 15:25 采纳率: 0%
浏览 9

在ajax上发送数据

Is this the correct way to send data to server on ajax request?

var xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
              alert(response);
            }
          };
          xhttp.open("GET", "https://myurl/", true);
          xhttp.send(JSON.stringify("{ action: 'search', mode: question}"));

Because I get this error 405 (Method Not Allowed - Action not found)

  • 写回答

1条回答 默认 最新

  • weixin_33709219 2017-01-17 15:30
    关注

    No, there are several issues with that:

    1. alert(response); will fail because there's no response variable; you'd probably want alert(xhttp.responseText).

    2. You're doing a GET, but then trying to send a POST body. You can't do that. GET information is in the URL, not the body.

    3. You're sending JSON (well, trying to), but not identifying it as JSON.

    4. You're passing a string into JSON.stringify, where normally you'd pass an object, not a string, as its job is to convert things to JSON strings.

    Assuming you mean to do a POST, and you really do want to send JSON (e.g., that the server is set up to accept JSON from the client), then minimal changes would be:

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            alert(xhttp.responseText);                                    // 1
        }
    };
    xhttp.open("POST", "https://myurl/", true);                           // 2
    xhttp.setRequestHeader("Content-Type", "application/json");           // 3
    xhttp.send(JSON.stringify({ action: 'search', mode: question}));      // 4
    

    Note that I'm assuming question is an in-scope variable in that.

    评论

报告相同问题?

悬赏问题

  • ¥15 java代码写在记事本上后在cmd上运行时无报错但又没生成文件
  • ¥15 关于#python#的问题:在跑ldsc数据整理的时候一直抱这种错误,要么--out识别不了参数,要么--merge-alleles识别不了参数(操作系统-linux)
  • ¥15 PPOCRLabel
  • ¥15 混合键合键合机对准标识
  • ¥100 现在不懂的是如何将当前的相机中的照片,作为纹理贴图,映射到扫描出的模型上
  • ¥15 魔霸ROG7 pro,win11.息屏后会显示黑屏,如图,如何解决?(关键词-重新启动)
  • ¥15 有没有人知道这是哪里出了问题啊?要怎么改呀?
  • ¥200 C++表格文件处理-悬赏
  • ¥15 Windows Server2016本地登录失败
  • ¥15 复合卡卡号轨道写入芯片卡