简体   繁体   中英

Call a C# webmethod from Ajax

I need to make a call to a webmethod that is defined in this class

<%@ 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

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 !! 错误图片

You are getting ThreadAbort response due to using of 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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