【问题标题】:Undefined Error on asp.net web-service call from external HTML page从外部 HTML 页面调用 asp.net Web 服务时出现未定义错误
【发布时间】:2013-12-16 10:36:08
【问题描述】:

我对 asp.net 和 web 服务很感兴趣。 我正在开发调用 asp.net web-service 的 HTML 5 应用程序。 我已经在 IIS7 上发布了我的 asp.net Web 服务,它工作正常,但是当我通过外部 HTML 5 JQuery 调用 Web 服务时,它给了我未定义的错误。

以下是我的网络服务代码:

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

[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 Service : System.Web.Services.WebService
{
    public Service () {

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

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


}

我的 Jquery 代码是:

// JavaScript Document
 $(document).ready(function() {

         $.ajax({
                type: "POST",
                url: "http://localhost/mywebserice/Service.asmx?op=HelloWorld",
                Content-Type: 'application/x-www-form-urlencoded',
                dataType: "xml",
                data: '{}',
                 success: function(){
                    alert("Success");
                },
                error: function(){
                    alert("Error");
                }
        });
});

我的 HTML5 代码是:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="jquery-1.10.2.js"></script>
<script type="text/javascript" src="newJS.js"></script>
</head>

<body>
</body>

</html>

谁能帮我解决这个问题?

【问题讨论】:

标签: c# asp.net html web-services jquery


【解决方案1】:

你的 jQuery ajax 设置属性错误。

首先,没有Content-Type这样的属性。使用contentType

其次,您指定了错误的 url 结构。 ajax url的结构应该是这样的:

   domain/ServiceName.asmx/MethodName?anyParamters=value

如果你调用webservice的页面和webservice属于同一个域,你也可以指定相对url,即,

   ~/ServiceName.asmx/MethodName?anyParamters=value

把你的 ajax 函数改成这样:

$.ajax({
         type: "POST",
         url: "http://localhost/mywebserice/Service.asmx/HelloWorld",
         contentType: 'application/x-www-form-urlencoded',
         dataType: "xml",
         data: {},
         success: function (msg) {
              alert($(msg).text());
              //console.log($(msg).text());
         },
         error: function(xhr, status, error){
                  console.log("Error");
          }
});

您可以阅读有关 jQuery ajax here 的所有可能属性。试一试

【讨论】:

    猜你喜欢
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 2016-01-25
    • 1970-01-01
    相关资源
    最近更新 更多