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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵