NetworkError:无法在'XMLHttpRequest'(ajax,WebAPI)上执行'send'

时间:2017-03-03 09:16:16

标签: javascript jquery ajax asp.net-web-api

我正在尝试向C#WebAPI发出POST ajax请求,但我似乎无法获得任何信息。

当我点击我网站上的按钮时,我可以看到服务器传回了这个错误:

"NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://120.96.86.139/api/SingleLoginPOST/'."

enter image description here

我已添加标题:

<meta http-equiv="Access-Control-Allow-Origin" content="*" />
<meta http-equiv="Access-Control-Allow-Headers" content="Content-Type" />
<meta http-equiv="Access-Control-Allow-Methods" content="POST" />

我该如何解决这个问题。谢谢。

代码:

var ip;

$.get("http://ipinfo.io", function(response) {
  ip = response.ip;
  console.log(ip);
}, "jsonp");


$(document).ready(function() {
  $(document).on('click', '#loginbtn', function() {

    var username = $("input#inpAcc").val();
    var password = $("input#inpPwd").val();
    var lenthl = $("input#inpAcc").val().lenth;


    if (username != "") {
      if (password != "") {
        var data = {
          Acc: username,
          Pwd: password,
          ip: ip

        };
        var dataRes = JSON.stringify(data);
        var APIurl = "http://120.96.86.139/api/SingleLoginPOST/";

        $.ajax({
          async: false,
          headers: {
            "cache-control": "no-cache"
          },

          contentType: 'application/jsonp; charset=utf-8',

          type: "POST",
          data: dataRes,
          dataType: "JSON",
          dataType: 'json',
          crossDomain: true,
          url: APIurl,
          async: false,
          withCredentials: true,

          contentType: 'application/jsonp; charset=utf-8',
          headers: {
            "Content-Type": "application/json",
            "X-HTTP-Method-Override": "POST"
          },
          error: function(xhr, status, p3, p4) {
            var err = "Error " + " " + status + " " + p3;
            console.log(xhr);
            console.log(status);
            console.log(p3);
            console.log(p4);
            if (xhr.responseText && xhr.responseText[0] == "{")
              err = JSON.parse(xhr.responseText).message;
            console.log(err);
          },
          success: function(data) {
            var i = 0;
            $.each(data, function(key, value) {

              window.sessionStorage["ACC"] = username;
              window.sessionStorage['PWD'] = password;               
              window.sessionStorage['NAME'] = value.name;
              window.location.assign("PersonMenu.html");
              console.log(value.name);

              console.log(data.message);
              console.log(data.html);


            })
          }
        });
      } else {
        alert("P");
      }

    } else {
      alert("A");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Access-Control-Allow-Origin" content="*" />
<meta http-equiv="Access-Control-Allow-Headers" content="Content-Type" />
<meta http-equiv="Access-Control-Allow-Methods" content="POST" />


<div class="form" id="form">
  <form class="login-form" method="POST">
    <input type="text" id="inpAcc" placeholder="Account" />
    <input type="password" id="inpPwd" placeholder="Password " />
    <input id="loginbtn" type="button" value="login" />
  </form>
</div>

的WebAPI:

1.WebConfig

   <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <!--<add name="Access-Control-Allow-Headers" value="Content-Type" />-->
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>

2.Controller

    public class SingleLoginPostController : ApiController
    {
        [HttpPost][HttpGet][HttpOptions][HttpDelete][HttpPut]

        public List<SingleLoginModel> SingleLoginPost([FromBody] SingleLoginPostModel SingleLoginPost)
        {

//...........
    }
    }

3.Model

 public class SingleLoginModel
{
    public string no { set; get; }
    public string name { set; get; }
    public string dept { set; get; }
    public string titel { set; get; }
    public string ret { set; get; }
    public string strError { set; get; }
}

public class SingleLoginPostModel
{
    public string Acc { set; get; }
    public string Pwd { set; get; }
    public string ip { set; get; }
}

2 个答案:

答案 0 :(得分:0)

也许你可以将你的ajax async:false更改为async:true 或删除异步,因为它是默认的真实

答案 1 :(得分:0)

将此行添加到网络服务属性

[System.Web.Script.Services.ScriptService]