无法执行ajax post操作

时间:2017-04-21 09:40:22

标签: javascript jquery json ajax

enter image description here我有以下json数据:

[
  {
    "Password": "tedd",
    "Username": "john",
    "status": true
  }
]

我想使用post方法消费

<label for="Username">Username:</label>
<input type="text" id="txtUserName" placeholder="Enter UserName"/>
<label for="Password">Password</label>
<input type="text" id="txtPass" placeholder="Enter Password" />
<input type="button" onclick="loginc()" value="Click Me" />

应用逻辑:

function loginc() {   
var username = document.getElementById("txtUserName").value;
if (username == "") {
    alert("Please enter the valid name");
    return false;
}

var password = document.getElementById("txtPass").value;
if (password == "") {
    alert("Please enter valid password");
}
var urlink = "http://192.168.0.112/Service1.svc/getlogin";

var datat = { Username: "username", Password: "password" };



$.ajax({
    type: 'POST',
    url: urlink,
    dataType: "json",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",

    data:datat,

    success: function (resp) {                
        alert(resp);
        if (resp.length != 0) {
            alert("Logged On");
        } else {
            alert("Wrong Credentials");
        }

    },
    error: function (e) {

        alert("Invalid");

    }
});

所以这里的问题是,当我输入用户名和密码时,点击按钮而不是验证我没有得到任何响应,并且它在错误中显示错误的凭据。

This is the result im getting in the post man

2 个答案:

答案 0 :(得分:3)

var datat = { Username: "username", Password: "password" };

在这里,您要发送文字字符串usernamepassword而不是变量。删除引号:

var datat = { Username: username, Password: password };

答案 1 :(得分:2)

一种解决方案是将参数附加到url

var datat = { Username: username, Password: password };

$.ajax({
   type: 'POST',
   url: urlink+'?username='+username+'&password='+password,
   dataType: "json",
   contentType: "application/x-www-form-urlencoded; charset=UTF-8",
   data:datat,
   success: function (resp) {                
      alert(resp);
      if (resp.length != 0) {
        alert("Logged On");
      } else {
        alert("Wrong Credentials");
      }

   },
   error: function (e) {
      alert("Invalid");
   }
});

另一种解决方案是使用JSON.stringify()方法发送对象。

contentType是您要发送的数据类型,因此您需要application/json;默认为application/x-www-form-urlencoded; charset=UTF-8.

如果您使用application/json,则必须使用JSON.stringify()才能发送JSON个对象。

JSON.stringify()javascript对象转换为json文本并将其存储在字符串中。

$.ajax({
   type: 'POST',
   url: urlink,
   dataType: "json",
   contentType: "application/json",
   data:JSON.stringify(datat),
   success: function (resp) {                
      alert(resp);
      if (resp.length != 0) {
        alert("Logged On");
      } else {
        alert("Wrong Credentials");
      }

   },
   error: function (e) {
      alert("Invalid");
   }
});