1

我正在创建一个 asmx Web 服务。在项目名称上的 Visual Studio 2012 中,我右键单击并添加了一个 Web 服务名称UserDetails.asmx

现在我正在尝试在 js 文件中使用 Web 服务。像这样

$.ajax({
    type: "POST",
    url: "UserDetails.asmx/HelloWorld",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
       alert('success');
    },
    error: function () {
        alert("Error");
    }
});

POST http://192.168.9.185/GPS/UserDetails.asmx/HelloWorld 500 (Internal Server Error)显示错误

我的代码中是否有任何错误,或者我遗漏了一些东西,所以它显示错误。我的 Asmx 页面

<%@ WebService Language="C#" CodeBehind="~/App_Code/UserDetails.cs" Class="UserDetails" %>

我的代码背后

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

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

public UserDetails () {

    //Uncomment the following line if using designed components 
    //InitializeComponent(); 
}

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

}
4

1 回答 1

0

编辑

简短回答:只需取消注释 [System.Web.Script.Services.ScriptService]

通过使用深入挖掘错误消息

error: function (xhr,status, error) {
        alert("Error");
       }

并检查 xhr 发现实际错误是其他错误(只能从脚本调用类定义中具有 [ScriptService] 属性的 Web 服务)。

I used [WebMethod] in my aspx code behind and whenever I received such message, I found out that there was an error in the data I am passing. So try adding data:"{}", in your $.ajax()

as described in this post

When making a read-only request, the empty data parameter is the key. For reasons unknown, jQuery does not properly set the specified content-type when there is no data included.

于 2013-02-05T07:48:07.203 回答