admin管理员组

文章数量:1324877

I have used JQuery example to send form data and receive back JSON data. Now I would like to do the same thing in plain/vanilla Javascript. Here is example of my JQuery code:

$('.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:

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. If anyone can help me with problem please let me know. Thank you.

I have used JQuery example to send form data and receive back JSON data. Now I would like to do the same thing in plain/vanilla Javascript. Here is example of my JQuery code:

$('.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:

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. If anyone can help me with problem please let me know. Thank you.

Share asked Jan 31, 2018 at 21:01 espresso_coffeeespresso_coffee 6,11012 gold badges94 silver badges220 bronze badges 2
  • 3 "I think that something is wrong in way how I handle response with JSON data" How so? you currently aren't handling it at all aside from logging it. – Kevin B Commented Jan 31, 2018 at 21:05
  • 1 you don't handle json in your vanilla response, hard to say what's wrong... – dandavis Commented Jan 31, 2018 at 21:05
Add a ment  | 

1 Answer 1

Reset to default 7

Optimally, for Firefox/Chrome/IE and legacy IE support, first determine the request type:

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.";
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;
       }
    }
}

本文标签: javascriptHow to send AJAX post request and receive back JSON data in Vanilla JSStack Overflow