【问题标题】:Is it possible to combine a GET and POST in Javascript?是否可以在 Javascript 中结合 GET 和 POST ?
【发布时间】:2016-09-18 12:21:56
【问题描述】:

我有 javascript 代码应该登录(即向服务器发送一些信息),然后收到回复 JSON 消息。我知道这是可行的,首先做一个帖子,然后在异步响应中,当它完成时,做一个获取。这需要两个回调函数和两条消息。

我只是想知道是否有任何方法可以将 JSON 作为查询的一部分进行获取和发送,以便只有一个请求/响应而不是两个。

这是我写的一个示例帖子:

function post(url, payload, callback) {
  payload = JSON.stringify(payload);
  var http = new XMLHttpRequest();
  http.open("POST", location.pathname + url, true);

  http.setRequestHeader("Content-type", "application/json");

  http.onreadystatechange = function () {
    if (http.readyState === 4 && http.status !== 200) {
      callback(false, http.response);
    } else if (http.readyState === 4 && http.status === 200) {
      callback(true, http.response);
    }
    return;
  };

  http.send(payload);
}

如果我想取回 JSON,我该怎么办?

是否像将 POST 更改为 GET 并查看以下内容一样简单: 返回时http.responseText?

【问题讨论】:

  • 1次通话没问题。必须在服务器端处理。
  • 我认为服务器通过 post (stdin) 接收参数并通过 stdout 回复。我编辑了问题以显示 javascript,我在问如何编写客户端代码。
  • 只需要在回调函数中解析响应即可。

标签: json post get


【解决方案1】:

如果您正在执行任何登录功能,则应始终使用 HTTP POST 方法。

您可以使用 AJAX (W3schools documentation about AJAX) 来处理通过 POST 发送登录表单,然后在同一代码块中处理响应。下面是一个例子。

$('#login-form').submit(function(e) {
    e.preventDefault(); // Prevents the page from refreshing
    // serializes the form data with id login-form
    var formData = $(this).serialize();
    $.ajax({
        type: 'POST',
        data: formData,
        contentType: 'application/x-www-form-urlencoded',
        dataType: 'json',
        url: $(this).attr('action'),

        //if your server sends a status OK message handle the response
        //data will be the JSON response from the server

        success: function(result,status,xhr) {
            var jsonRes = JSON.parse(result); // parse the JSON object
            console.log(jsonRes);
        },

        //if there was an error with your request the server will send
        // an error response code and it is handled here
        error: function(xhr,status,error) {
            console.log(error);
        }
    });

【讨论】:

  • 我特别想避免使用 jQuery。这很好,但我想在 javascript 级别查看代码在做什么。感谢您的链接
猜你喜欢
  • 1970-01-01
  • 2010-10-26
  • 1970-01-01
  • 2016-04-29
  • 2013-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多