【问题标题】:jquery function not being called by web apiweb api没有调用jquery函数
【发布时间】:2015-02-26 12:42:59
【问题描述】:

当数据通过 jquery 输入 html 页面时,我有一个 web api 可以在表中发布数据。 web api函数如下:

   public HttpResponseMessage Post(User user)
        {

            if (ModelState.IsValid)
            {
                db.Users.Add(user);
                db.SaveChanges();

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.UserID }));
                return response;
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }

带有jquery脚本的html页面是:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>

    <div>
    <h2>All users</h2>
    <ul id="users" />
  </div>

<div>
    <h2>Insert New User</h2>
    First Name : <input type="text" id="firstName"  /><br />
    Last Name : <input type="text" id="lastName"  /><br />
    City  : <input type="text" id="city"  /><br />
    Email : <input type="email" id="email"  /><br />
    Password : <input type="password" id="password"  /><br />
    Phone number:    <input type="number" id="phone"  /><br />
    <input type="button" id="btnsave" value="Save" onclick="Post();" />
    <p id="P1" />
  </div>

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>

  <script>
      var uri = 'api/user';

      $(document).ready(function () {
          // Send an AJAX request
          getuserlist();
      });


      function getuserlist() {
          $.getJSON(uri)
             .done(function (data) {
                 $('#users').html('');
                 // On success, 'data' contains a list of users.
                 $.each(data, function (key, item) {
                     // Add a list item for the user.

                     $('<li>', { text: formatItem(item) }).appendTo($('#users'));
                 });
             });
      }
      function formatItem(item) {
          return 'email:' + item.email + ' and First Name:' + item.firstName + ' and Last Name: ' + item.lastName;
      }

      function Post() {
          jQuery.support.cors = true;
          var source = {
              'firstName': $('#firstName').val(),
              'lastName': $('#lastName').val(),
              'email': $('#email').val(),
              'phone': $('#phone').val(),
              'city': $('#city').val(),
              'password': $('#password').val()
          }
          $.ajax({
              type: "POST",
              dataType: "json",
              url: "/api/user",
              data: source,
              success: function (data) {
                  var strResult = "<table><th>Returned Message</th>";
                  // $.each(data, function (index, data) {
                  strResult += "<tr><td> " + source.email + " </td></tr>"
                  strResult += "</table>";
                  $("#divResult").html(strResult);
              },
              error: function (x, y, z) {

                  var strResult = "<table><th>Error Message</th>";
                  // $.each(data, function (index, data) {
                  strResult += "<tr><td> " + x.responseText + " </td></tr>"
                  strResult += "</table>";
                  $("#divResult").html(strResult);
                  // alert(x + '\n' + y + '\n' + z);
              }
              //success: function (data) {
              //    //alert(data);
              //    getuserlist();
              //    // alert(jQuery.parseJSON(data));

              //},
              //error: function (error) {
              //    jsonValue = jQuery.parseJSON(error.responseText);
              //    //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
              //}
          });
      });
  </script>
</body>
</html>

当我单击按钮添加新用户时,post() 函数不起作用。 页面保持不变,无操作,无错误。

请帮忙! 谢谢!

【问题讨论】:

  • 你的帖子功能在哪里?
  • 进入脚本标签
  • 哎呀,对不起,我没有注意到,无论如何,你能验证 firebug/fiddler 中的错误吗?
  • 你为什么启用这个CORSjQuery.support.cors = true;?你要跨域请求吗?
  • 当我点击保存按钮时什么都没有发生......是的,我稍后会需要它。

标签: c# jquery asp.net json asp.net-web-api


【解决方案1】:

首先,您要发布到的网址应该是"/api/user/Post"

输出

我必须修复发布的代码中的其他几个JavaScript 错误。正如其他人在 cmets 中提到的那样,这些错误显示在控制台中。了解如何使用开发者工具进行调试非常宝贵,值得花时间学习。

这里是修复的更新代码:

  <div>
    <h2>All users</h2>
    <ul id="users" />
  </div>

<div>
    <h2>Insert New User</h2>
    First Name : <input type="text" id="firstName"  /><br />
    Last Name : <input type="text" id="lastName"  /><br />
    City  : <input type="text" id="city"  /><br />
    Email : <input type="email" id="email"  /><br />
    Password : <input type="password" id="password"  /><br />
    Phone number:    <input type="number" id="phone"  /><br />
    <input type="button" id="btnsave" value="Save" onclick="Post();" />
    <p id="P1" />
  </div>

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>

  <script>
     var uri = 'api/user';

      $(document).ready(function () {
          // Send an AJAX request
          getuserlist();
      });


      function getuserlist() {
          $.getJSON(uri)
             .done(function (data) {
                 $('#users').html('');
                 // On success, 'data' contains a list of users.
                 $.each(data, function (key, item) {
                     // Add a list item for the user.

                     $('<li>', { text: formatItem(item) }).appendTo($('#users'));
                 });
             });
      }
      function formatItem(item) {
          return 'email:' + item.email + ' and First Name:' + item.firstName + ' and Last Name: ' + item.lastName;
      }

      function Post() {
          jQuery.support.cors = true;
          var source = {
              'firstName': $('#firstName').val(),
              'lastName': $('#lastName').val(),
              'email': $('#email').val(),
              'phone': $('#phone').val(),
              'city': $('#city').val(),
              'password': $('#password').val()
          }
          $.ajax({
              type: "POST",
              dataType: "json",
              url: "/api/user/Post",
              data: source,
              success: function (data) {
                  var strResult = "<table><th>Returned Message</th>";
                  $.each(data, function (index, data) {
                      strResult += "<tr><td> " + source.email + " </td></tr>"
                      strResult += "</table>";
                      $("#divResult").html(strResult);
                  });
              },
              error: function (x, y, z) {

                  var strResult = "<table><th>Error Message</th>";
                  $.each(x, function (index, data) {
                      strResult += "<tr><td> " + x.responseText + " </td></tr>"
                      strResult += "</table>";
                      $("#divResult").html(strResult);
                      // alert(x + '\n' + y + '\n' + z);
                  });
              }
              //success: function (data) {
              //    //alert(data);
              //    getuserlist();
              //    // alert(jQuery.parseJSON(data));

              //},
              //error: function (error) {
              //    jsonValue = jQuery.parseJSON(error.responseText);
              //    //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
              //}
          });
      };
  </script>

我还假设您的User 对象如下:

public class User
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string email { get; set; }
    public string phone { get; set; }
    public string city { get; set; }
    public string password { get; set; }
}

【讨论】:

  • 我的也可以。有一些验证异常我没有处理,应该处理。
猜你喜欢
  • 1970-01-01
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多