【问题标题】:What is wrong with my asp.net web service call我的 asp.net Web 服务调用有什么问题
【发布时间】:2014-10-22 11:09:56
【问题描述】:

我正在尝试从 jquery 使用 Web 服务方法,但我在下面收到此错误

Uncaught SyntaxError: Unexpected token

它指向我的服务方法 url。下面是我的代码,

$("#btnDialog").click(function () {
    var test = $("#hfID").val();
    testService(test);
    $("#dialog").dialog("open");
});

function testService(test) {
    $.ajax({
        crossDomain: true,
        type: "POST",
        url: "http://localhost:64461/Service1.asmx?op=HelloWorld",
        data: test,
        contentType: "application/json; charset=utf-8",
        dataType: "jsonp",
        success: function(json) {
            $("#lblID").text(json.responseText);
        },
        failure: function(response) {
            alert("Did not work");
        }
    });
}

网络服务方式是

public class Service1 : System.Web.Services.WebService
{

    [WebMethod]
    public string HelloWorld(string id)
    {
        string toReturn = null;
        if (string.IsNullOrEmpty(id))
        {
            toReturn = "recieved but nothing";
        }
        else
        {
            Class1 class1 = new Class1();
            class1.GetName();
            toReturn = class1.GetName();
        }
        return toReturn;
    }
}

【问题讨论】:

  • 你确定它应该是 jQuery 中的 POST 类型调用吗?

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


【解决方案1】:

试试这个:

function testService(test) {
$.ajax({
    crossDomain: true,
    type: "POST",
    url: "http://localhost:64461/Service1.asmx/HelloWorld",
   data: "{'id':'" + test + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "jsonp",
    success: function(json) {
        $("#lblID").text(json.responseText);
    },
    failure: function(response) {
        alert("Did not work");
    }
 });
}

【讨论】:

  • 我之前尝试过,但我在使用该解决方案时遇到此错误,但仍然无法正常工作。资源解释为脚本,但使用 MIME 类型 text/html 传输
  • 确保您的网络服务可以被javascript调用。 [System.Web.Script.Services.ScriptService] 公共类 Service1 : System.Web.Services.WebService
  • 它使用 System.Web.Script.Services;... 并且已经存在
【解决方案2】:

您的 [WebMethod] 属性告诉端点返回 XML。

您的 JS 代码要求 JSON 并期待 JSONP 响应。因此响应中有一个无效的令牌,即 XML 的第一个 <

一种选择是处理 XML 而不是 JSON。

另一种选择是将ScriptMethod 属性与WebMethod 属性一起添加,以便您可以控制响应。

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-19
    • 2017-07-01
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    相关资源
    最近更新 更多