Jquery ajax vs XMLHttpRequest

时间:2014-11-29 01:04:12

标签: javascript jquery ajax xmlhttprequest

这里我有两个相同的请求:jquery ajax和XMLHttpRequest但JQ ajax不工作......所以想知道有什么区别:

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': '*'
        }
});


}); 
});

这个ajax请求不起作用......给我404错误......

的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");

此请求工作正常,但我需要知道有什么区别,两者都调用POST url ...

我需要在JQ ajax请求中更改工作吗?

1 个答案:

答案 0 :(得分:1)

Access-Control-Allow-Origin是一个回复标题,因此它不应位于请求标题列表中:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#The_HTTP_response_headers

删除以下内容:

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

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