Ajax post方法不起作用显示状态代码400

时间:2017-08-04 15:17:49

标签: javascript jquery ajax

我的ajax代码无效。它显示错误

XMLHttpRequest cannot load http://xxx.xxx.xxx No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 400.

如何解决问题。我尝试过不同的标题。但不发布数据。请解决我的问题。 我的代码是

$http({
       method: "post",
       dataType:'json',
        url: res,
       crossDomain : true,
        data: {
            'name': $scope.name,
            'email': $scope.email,
             'text area': $scope.query

        },
headers: { 'Access-Control-Allow-Origin': '*' }
    }).then(function success(data) {


        alert("Message sent succesfully");
        /*var success=data.data.issuccess;
        if(success==true)
        {
          var name=data.data.username;
          var userid=data.data.userid;
          alert("Name= "+name+ "UserId="+userid);
        }*/




    });

这是正确的邮递员。但不是在ajax。 enter image description here

3 个答案:

答案 0 :(得分:1)

您必须在服务器上启用CORS。

请阅读:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

同时检查一下:

https://enable-cors.org/server.html

注意:我在阅读SLaks的评论后对此进行了更正。他是对的。

答案 1 :(得分:1)

问题是,http://xxx.xxx.xxx在其响应中没有发送正确的标头,因此您无法访问它。有关流程示例,请参阅https://fetch.spec.whatwg.org/#cors-protocol-examples

答案 2 :(得分:1)

我已经解决了这个问题。这是服务器端面临的问题。我改变代码是

$.ajax({
url: "http://xxx.xx.xx.xx/api/SendMail/SendEmail",
type: "POST",
async: false,
ContentType: "application/json; charset=utf-8",
data:  {
            'subject': "Contact us from SQU app",
            'message': msgSQU

        },
crossOrigin: true,
dataType: "json",
success: function (response) {
$resData = response;
//alert("Su");
showConfirm("Your Feedback succesfully send");


},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
//console.log(textStatus, errorThrown);
}
});

现在工作正常。

相关问题