使用jquery ajax从asmx文件返回文本

时间:2013-09-02 07:55:41

标签: jquery asp.net ajax web-services asmx

我无法看到这个简单代码的工作问题

setdata.asmx
[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 setdata : System.Web.Services.WebService {

public setdata () {

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

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

}

my jquery
$.ajax({
            method: "POST",
            url: "setdata.asmx/HelloWorld",
            contentType: "text/plain; charset=utf-8",
            //data: { category: category },
            success: function (txt) {
                alert(txt);
            },
            error: function(jqXHR, textStatus, errorThrown ){
          alert("Error:"+jqXHR + textStatus + errorThrown);
        }
        });

错误是:

[object Object]errorInternal Server Error

我该如何解决呢?

我猜到了问题: -     jquery位于我的网站名为web1的admin文件夹中的default.aspx页面内     我发布的网址只是setdata.asmx,     服务器是否在根目录的当前目录中查找setdata.asmx

2 个答案:

答案 0 :(得分:1)

尝试更新jQuery脚本以检查错误:

 $.ajax({
        method: "POST",
        url: "<%= this.ResolveUrl("~/setdata.asmx")%>/HelloWorld",
        contentType: "text/plain; charset=utf-8",
        //data: { category: category },
        success: function (txt) {
            alert(txt);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("Error:" + jqXHR + textStatus + errorThrown);
        }
    });

这应该简化调试。 Aldo使用ResolveUrl方法获取服务的正确地址。

答案 1 :(得分:0)

请确保您已添加必要的web.config条目以从客户端脚本调用asmx服务。检查以下网址:

http://encosia.com/asmx-scriptservice-mistakes-installation-and-configuration/