简体   繁体   English

从Ajax调用C#网络方法

[英]Call a C# webmethod from Ajax

I need to make a call to a webmethod that is defined in this class 我需要调用此类中定义的Web方法

<%@ WebService Language="C#" Class="emt7anReyady.myService" %>

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Linq;
using System.Web.Security;

namespace emt7anReyady
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // 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 myService : System.Web.Services.WebService
    {
        [WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public void test()
        {
            Context.Response.Redirect("http://www.google.com");
        }
    }
}

and I have make an Ajax call like this one 我已经像这样打了一个Ajax电话

function getData() {
                 $.ajax({
                     type: "POST",
                     url: "myService.asmx/test",
                     data: "{}",
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     success: function () {
                         alert("succesed")
                     },
                     failure: function () {
                         alert("faild")
                     }
                 });
             }


the problem that the call is failed and in the chrome console I get this !! 呼叫失败的问题,在chrome控制台中,我得到了这个! 错误图片

You are getting ThreadAbort response due to using of Response.Redirect . 您由于使用Response.Redirect而获得ThreadAbort Response.Redirect

It is not exactly clear what you are trying to achieve with this code - if you want proxy some other site you need to read and forward response... 目前尚不清楚您要使用此代码实现的目标-如果要代理其他站点,则需要读取和转发响应...

It is because of Response.Redirect you are using in your WebMethod. 这是因为您在WebMethod中使用了Response.Redirect。 If you really want to redirect to some other page, do it from the success block. 如果您确实要重定向到其他页面,请从成功块开始。

.
.

success: function () {
                     window.open('http://www.google.com');
                 },
.
.

you can also make use of document.location instead of window.open 您还可以使用document.location而不是window.open

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM