简体   繁体   中英

Jquery ajax vs XMLHttpRequest

Here I have two for me the same request: jquery ajax and XMLHttpRequest but JQ ajax dont work... SO want to know what is the difference:

JQ ajax:

var urlAjax = "http://www.agroagro.com/v1/register";

$.ajax({
type: "POST",
url: urlAjax,
contentType: "application/x-www-form-urlencoded",
data: {
                    name: "Mile3",
                    email: "new1@new.com",
                    password: "face1book"
                },
  crossDomain:true, 
  success: function(data) { console.log(data); },
error: function(data) {console.log(data); },
dataType: 'json',
beforeSend: function (xhr) {
            xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
        },
        headers: {
            'Access-Control-Allow-Origin': '*'
        }
});


}); 
});

and this ajax request dont work... give me 404 error...

XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {"done"}
}

xhr.open("POST","http://agroagro.com/v1/register",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("name=Henry&email=Ford@ford.com&password=1234");

This request work fine, but I need to know what is the difference, the both call POST url...

Also what I need to change in my JQ ajax request to work?

Access-Control-Allow-Origin is a response header so it shouldn't be on the list of request headers: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#The_HTTP_response_headers

Remove the following:

beforeSend: function (xhr) {
    xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
}

and

headers: {
    'Access-Control-Allow-Origin': '*'
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM