在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)

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.