无法使用jquery ajax调用aspx页面Web方法

问题描述 投票:2回答:3

尝试在aspx页面上调用web方法时获取aspx页面html。这是jQuery代码

  $(function () {
        $.ajax({
            type: 'POST',
            url: 'Default.aspx/Hello',
            data: "{}",
            async: false,
            success: function (response) {
                console.log('Success: ', response);
            },
            error: function (error) {
                console.log('Error: ', error);
            }
        });
    });

这是Web方法代码

 [System.Web.Services.WebMethod]
    public static string Hello()
    {
        string returnString = "hoiiiiiii";
        return returnString;
    }

任何人都可以指出可能出错的地方。

c# javascript jquery asp.net ajax
3个回答
3
投票

两件事情:

  1. 您在jQuery contentType函数中缺少.ajax()
  2. 您需要考虑JSON响应中的.d值。 $.ajax({ type: "POST", url: "Default.aspx/Hello", data: "{}", async: false, contentType: "application/json; charset=utf-8", dataType: "json", success: function(result) { if (result.hasOwnProperty("d")) { // The .d is part of the result so reference it // to get to the actual JSON data of interest console.log('Success: ', result.d); } else { // No .d; so just use result console.log('Success: ', result); } } });

注意:.d语法是Microsoft在ASP.NET AJAX的ASP.NET 3.5版本中提供的反XSS保护;因此检查.d财产是否存在。


2
投票

你可以像这样编码:(这对我很有用)我使用了CDN的jquery:“http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js

public class MyClass
{
    public string myName
    {
        get { return "Hello"; }
    }
}

在您的aspx.cs页面中:

[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json, UseHttpGet = true)]
public static object MyMethod()
{
    return new MyClass();
}

在您的ASPX页面中:

$.ajax({
            url: "somepage.aspx/MyMethod",
            data: {},
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            type: "GET",
            success: function (data) {
                if (data.hasOwnProperty("d"))
                    alert(data.d.myName);
                else
                    alert(data);
            },
            error: function (reponse) {
                alert(reponse);
            }
        });

0
投票

试试这个 -

$(function () {
    $.ajax({
        type: 'GET',
        url: 'Default.aspx/Hello',
        contentType: "application/json; charset=utf-8",
        async: false,
        dataType: "json",
        success: function (response) {
            console.log('Success: ', response);
        },
        error: function (error) {
            console.log('Error: ', error);
        }
    });
});

和网络方法 -

[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string Hello()
{
    string returnString = "hoiiiiiii";
    return returnString;
}
© www.soinside.com 2019 - 2024. All rights reserved.