简体   繁体   English

如何在Vanilla JS中发送AJAX发布请求并接收回JSON数据?

[英]How to send AJAX post request and receive back JSON data in Vanilla JS?

I have used JQuery example to send form data and receive back JSON data. 我已使用JQuery示例发送表单数据并接收回JSON数据。 Now I would like to do the same thing in plain/vanilla Javascript. 现在,我想在普通/原始Javascript中做同样的事情。 Here is example of my JQuery code: 这是我的JQuery代码的示例:

$('.frmSubmitData').on('submit', function(e){
    e.preventDefault();
    var formData = $('#myForm').serialize();
    console.log(formData);

    $.ajax({
        type: 'POST',
        encoding:"UTF-8",
        url: 'Components/myTest.cfc?method=testForm',
        data: formData,
        dataType: 'json'
    }).done(function(obj){
        if(obj.STATUS === 200){
            console.log(obj.FORMDATA);
        }else{
            alert('Error');
        }
    }).fail(function(jqXHR, textStatus, errorThrown){
        alert("Error: "+errorThrown);
    });
});

And here is what I have so far in plain JS: 这是到目前为止我在普通JS中的功能:

function sendForm(){
   var formData = new FormData(document.getElementById('myForm')),
       xhr = new XMLHttpRequest();

    xhr.open('POST', 'Components/myTest.cfc?method=testForm');
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        if (xhr.status === 200) {
            console.log(xhr.responseText);
        }else if (xhr.status !== 200) {
            alert('Request failed.  Returned status of ' + xhr.status);
        }
    };
    xhr.send(formData); 
}

I think that something is wrong in way how I handle response with JSON data. 我认为我处理JSON数据响应的方式出了问题。 If anyone can help me with problem please let me know. 如果有人可以帮助我解决问题,请告诉我。 Thank you. 谢谢。

Optimally, for Firefox/Chrome/IE and legacy IE support, first determine the request type: 最好,对于Firefox / Chrome / IE和旧版IE支持,首先确定请求类型:

function ajaxReq() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert("Browser does not support XMLHTTP.");
        return false;
    }
}

Then, send the request: 然后,发送请求:

var xmlhttp = ajaxReq();
var url = "http://random.url.com";
var params = "your post body parameters";
xmlhttp.open("POST", url, true); // set true for async, false for sync request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params); // or null, if no parameters are passed

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
       try {
           var obj = JSON.parse(xmlhttp.responseText);

           // do your work here

       } catch (error) {
           throw Error;
       }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何发送发布请求并在Rails中接收json - how to send a post request and receive json back in rails 如何从表单中收集数据并通过 ajax POST 发送(从 jQuery 到 Vanilla JS) - How to collect data from form and send it via ajax POST (from jQuery to Vanilla JS) 如何通过 $POST 从 ajax 发送 object 数据(从 jQuery 到 vanilla JS) - How to send object data through $POST from via ajax (from jQuery to vanilla JS) AJAX:如何在 vanilla JS 中通过 POST 发送简单参数 - AJAX: How to send a simple parameter by POST in vanilla JS 如何在 vanilla Nodejs 中将 JSON 数据发送回客户端 - How to send JSON data back to client in vanilla Nodejs 使用Vanilla JS将AJAX请求发送到Django视图 - Send AJAX request to Django view with vanilla JS 香草js中https上的Ajax POST请求 - Ajax POST request on https in vanilla js 如何使用 vanilla JavaScript AJAX 发布 JSON 或表单数据 - How to post JSON or form data with vanilla JavaScript AJAX 使用 vanilla javascript ajax [ASP.NET Core] 在同一个 POST 请求中上传文件和 Json 数据 - Upload file and Json data in the same POST request using vanilla javascript ajax [ASP.NET Core] Codeigniter,香草JS:发送Ajax发布请求,但未接收到php中的任何数据 - Codeigniter, Vanilla JS: Sending Ajax post request but not recieving any data in php
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM