Ajax在asp.net中调用Web服务

时间:2015-08-28 08:28:19

标签: c# asp.net ajax

无法加载资源:服务器响应状态为500(内部服务器错误)localhost:45562 / WebService1.asmx / btn

WebService无法通过ajax调用加载,如果我在WebForm.aspx.cs中编写相同的代码,一切都运行良好

WebForm1.aspx的

$(document).ready(function () {

        $("#btn").click(function () {
            sendAjaxRequest();
        });



        function sendAjaxRequest() {
            $.ajax({
                async: true,
                url: "WebService1.asmx/btn",
                type: "POST",
                data: "{ surname: 'Axakalov', name: 'Sunnatilla' }",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: responseOut,
                error: function (error) {
                    debugger;
                    alert(error);
                }
            });
        };


        function responseOut(response) {
            $("#out").html(response.d);
        }

    });

WebService1.asmx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebApplication9
{
/// <summary>
/// Summary description for WebService1
/// </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 WebService1 : System.Web.Services.WebService
{

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }


    [WebMethod]
    public string btn(string surname, string name)
    {
        return surname + " " + name;
    }

}

}

请帮忙,为什么找不到webservcise1.asmx

1 个答案:

答案 0 :(得分:1)

考虑到您已经提供了正确的网址..

您需要启用[System.Web.Script.Services.ScriptService]属性:

[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{   
    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }

    [WebMethod]
    public string btn(string surname, string name)
    {
        return surname + " " + name;
    }  
}