【问题标题】:How I can send json in request body with ajax ? just javascript and dont use jQuery如何使用 ajax 在请求正文中发送 json?只是 javascript,不使用 jQuery
【发布时间】:2021-03-06 16:58:51
【问题描述】:

如何使用 ajax 在正文请求中发送 json?只使用 Javascript,不要使用 jQuery !!! 有人可以帮忙 我提醒你不要使用jQuery!!!

【问题讨论】:

    标签: javascript ajax post frontend


    【解决方案1】:

    您可以创建像 jquery ajax 请求一样工作的函数。

    function AJAX(url, success, async) {
        if (window.XMLHttpRequest) {
            var request = new XMLHttpRequest;
        } else {
            // IE6 and IE5 (unnecessary)
            var request = new ActiveXObject("Microsoft.XMLHttp");
        }
        if (async) request.onReadyStateChange = function() {
            if (request.readyState == 4) {
                success(request.status, request.responseText);
            }
        };
        request.open("GET", url, async);
        request.send();
        if (!async) success(request.status, request.responseText);
    }
    

    【讨论】:

      【解决方案2】:

      我不明白这一点。如果您只需要请求一个 URL 并发送 JSON 正文,您可以通过 XMLHttpRequest 简单地实现它:

      var xhr = new XMLHttpRequest();
      var url = "url";
      xhr.open("POST", url, true);
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
              console.log('RESPONSE');
          }
      };
      var data = {"email": "hey@mail.com", "password": "101010"}; // JSON YOU SEND
      xhr.send(JSON.stringify(data));
      

      这里的原始答案:Sending a JSON to server and retrieving a JSON in return, without JQuery

      【讨论】:

        【解决方案3】:

        你可以试试这样的

        var xhr = new XMLHttpRequest;
        xhr.open('POST', '/your_url');
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.onreadystatechange = function() {
          if (xhr.readyState == 4 && xhr.status == 200) {
            // success
            console.log(xhr.responseText); 
          } else {
            // other
            console.log('Error, status code = ' + xhr.status + ', response = '+xhr.responseText);
          }
        };
        var payload = JSON.stringify({param1: 1, param2: 'hello'});
        xhr.send(payload);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-05-23
          • 2016-10-02
          • 2018-09-04
          • 1970-01-01
          • 2019-09-15
          • 1970-01-01
          • 2011-08-08
          • 2023-03-18
          相关资源
          最近更新 更多