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 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序