java - 通过Ajax与后端方法通信

标签 java html asp.net ajax angularjs

我正在尝试使用 Ajax 和 AngularJS 与方法进行通信,但没有收到响应,并且警报输出 未定义

Index.cshtml

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app="myApp">
// Displaying the table is working
    <div>
        <table class="table" ng-controller="UpdateController">
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Country</th>
            </tr>
            <tr ng-repeat="c in cities">
                <td>{{c.Id}}</td>
                <td>{{c.City1}}</td>
                <td>{{c.Country}}</td>
            </tr>
        </table>
    </div>
// Here I add the controller for adding records -->
    <div ng-controller="AddRecord">
        <form id="form1" ng-submit="send()">
            <table>

                <tr>
                    <td>City: </td>
                    <td>
                        <input type="text" id="txtCity" ng-model="addCity" />
                    </td>
                </tr>
                <tr>
                    <td>Country: </td>
                    <td>
                        <input type="text" id="txtCountry" ng-model="addCountry" />
                    </td>
                </tr>

                <tr>
                    <td>
                        <input type="submit" id="btnSubmit" value="Submit" />
                    </td>
                </tr>

            </table>
        </form>
    </div>

    <script>
        var app = angular.module('myApp', []);

        app.controller('UpdateController', function ($scope, $http) {
            $http.get("http://localhost:50366/api/cities")
            .success(function (response) { $scope.cities = response });

        });        

        app.controller('AddRecord', function ($scope, $http) {
// Function responsible for communicating with backend  
            $scope.send = function () {    
                $.ajax({
                    type: "POST",
                    url: "AddCity.asmx.cs/PostCity",
                    data: "{'city':'" + $scope.addCity + "','country':'" + $scope.addCountry + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        alert(msg.d);
                    },
                    error: function (msg) {
                        alert(msg.d);
                    }
                });
//Here is one I tried using text as the datatype:
            $.ajax({
                type: "POST",
                url: "AddCity.asmx/PostCity",
                data: "city=" + $scope.addCity + "&country=" + $scope.addCountry,
                dataType: "text",
                success: function (msg) {
                    alert(msg.d);
                },
                error: function (msg) {
                    alert(msg.d);
                }
            });

            };
        });

    </script>
</body>

</html>

AddCity.asmx 以及我尝试访问的方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using AngularWebApi.Models;
using AngularWebApi.Controllers;

namespace AngularWebApi.Views
{
    /// <summary>
    /// Summary description for AddCity
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class AddCity : System.Web.Services.WebService
    {

        [WebMethod]
        public string PostCity(string city, string country)
        {
            City newCity = new City();
            newCity.City1 = city;
            newCity.Country = country;
            //Eventually I want to add the city to the database
            CitiesController controller = new CitiesController();

            controller.PostCity(newCity);

            return "Posted!";
        }
    }
}

Index.cshtml 位于 Views/Home 中,AddCity.asmx 位于 Views 中。我也尝试使用 url: "../AddCity.asmx/PostCity"

编辑

我快速创建了一个新项目并进行了设置,发生了完全相同的事情,步骤如下:

  • 新的 Web API 项目
  • 新的 ADO.net 实体数据模型并将其链接到我的数据库
  • 新的 Web API 2 Controller ,其操作使用 Entity Framework 传递来自数据库的表和我从上一步获得的实体。

然后,我编辑 Index.cshtml 以将 API/CITIES 中的 XML 显示为表格。这次我在项目的根目录中添加了我的服务,并尝试使用 $.ajax POST 函数调用自动创建的 HelloWorld

我确实在 FF 错误控制台中看到警告。荷兰语直译:跨域请求被阻止:...

此外,错误是在ajax调用中触发的。据我所知,WebService 尚未到达。

这是我点击按钮时得到的完整回复:

<!DOCTYPE html>
<html>
    <head>
        <title>The resource cannot be found.</title>
        <meta name="viewport" content="width=device-width" />
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
         @media screen and (max-width: 639px) {
          pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
         }
         @media screen and (max-width: 479px) {
          pre { width: 280px; }
         }
        </style>
    </head>

    <body bgcolor="white">

            <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>

            <h2> <i>The resource cannot be found.</i> </h2></span>

            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

            <b> Description: </b>HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. &nbsp;Please review the following URL and make sure that it is spelled correctly.
            <br><br>

            <b> Requested URL: </b>/Home/MyWebService.asmx/HelloWorld<br><br>

            <hr width=100% size=1 color=silver>

            <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408

            </font>

    </body>
</html>
<!-- 
[HttpException]: A public action method &#39;MyWebService.asmx&#39; was not found on controller &#39;AngularTutorial.Controllers.HomeController&#39;.
   at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)
   at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
   at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
   at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
   at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
   at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
   at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
   at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
   at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
   at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->

编辑

Controller 中的POST方法:

// POST: api/Cities
        [ResponseType(typeof(City))]
        public IHttpActionResult PostCity(City city)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Cities.Add(city);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = city.Id }, city);
        }

最佳答案

嗯,我想我明白了:你尝试创建一个新的 POST-Method,但根据教程,城市 Controller 中已经有一个 POST-Method:

By clicking on Add, we are able to create the Cities Web API using the scaffolding. The created controller class will have a Web API for all the CRUD operations on the city table.

这意味着您只需将 ajax 调用发送到 http://localhost:50366/api/cities:

$.ajax({
       type: "POST",
       url: "http://localhost:50366/api/cities",
       data: "{'country':'" + country + "','name':'" + cityName + "'}",
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function (msg) {
             alert(msg.d);
       },
       error: function (msg) {
             alert(msg.d);
       }
      });

确保您只运行 1 个 Web 应用程序,这样可以避免不必要的问题。

顺便说一句。我不确定,如果 Controller 会接受 json 也许您需要将数据作为 xml 发送...

编辑: 我更新了json数据。您的城市对象有 3 个属性:countryidname。如果您发送 POST 请求,您将创建一个新对象,因此您不需要发送 id

对于 PUTDELETE(如果您想实现此功能),您需要将 id 添加到网址: http://localhost:50366/api/cities/:id

编辑2: 好的,xml 应该如下所示:

data: "<City><Country>" + country + "</Country><Name>" + cityName + "</Name></City>",

不要忘记更改:

contentType: "application/xml; charset=utf-8",
dataType: "xml",

关于java - 通过Ajax与后端方法通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31984063/

相关文章:

html - 使用 CSS 表进行多行复选框的 CSS 填充问题

javascript - 当我在不同的事件中使用它时,函数 javascript 不起作用

javascript - 使用jquery隐藏html元素后RequestVerificationToken值为空

ASP.NET_SessionId + OWIN Cookie 不会发送到浏览器

c# - ITextSharp 添加页码到合并的 pdf 中

java - 如何在 Retrofit onResponse 的方法中返回数据?

java - Grails:集成测试 Ajax 请求 - xhr

java - 通过smpp在Java中编码法语字符?

c# - 全局化找不到合适的资源

java - 一些Java关键字概念问题