简体   繁体   English

JQuery后面的代码中的call方法

[英]call method in code behind from JQuery

I am trying to execute a method in ASP.NET from Jquery 我正在尝试从Jquery在ASP.NET中执行方法

$.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "MyMessages.aspx?id=66&epslanguage=sv/test",
        data: "{}",
        dataType: "json",
        error: function(xhr, err) {
        alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
        alert("responseText: " + xhr.responseText);
            },
        success: function() {
            alert("it works" );
        }
    })

code behind: 后面的代码:

    [WebMethod]
    protected void test()
    {
        test.Text = "works";
    }

I get errormessage redayState: 4 and status 200 when I do this. 这样做时,我收到errormessage redayState:4和状态200。 I don't understand the problem. 我不明白这个问题。 I am vey new at this. 我对此很新。 :) :)

data: "{}",应该只是data: {},如果不使用,则将其删除。

as a first your method should be static and public so instead of this 首先,您的方法应该是静态的并且是公共的,因此

   [WebMethod]
protected void test()
{
    test.Text = "works";
}

it should be 它应该是

[WebMethod]
public static void test()
{
    test.Text = "works";
}

this is the first fix the second you can't access the test.text so if u wanna make sure it works you can write it in this way 这是第一个解决方案,第二个是您无法访问test.text的解决方案,因此,如果您想确保它能正常工作,可以用这种方式编写

$.ajax({
    type: "POST",
    contentType: "application/json",
    url: "MyMessages.aspx/test",
    data: "{}",
    dataType: "json",
    error: function(xhr, err) {
    alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
    alert("responseText: " + xhr.responseText);
        },
    success: function() {
        alert("it works" );
        // and here use jQuery to set the control test
        $("#<%=test.ClientID%>".text("Works");
    }
})

so your final code should be like this 所以你的最终代码应该是这样的

 [WebMethod]
public static void test()
{
    //test.Text = "works";
}

and Ajax method 和Ajax方法

   $.ajax({
    type: "POST",
    contentType: "application/json",
    url: "MyMessages.aspx/test",
    data: "{}",
    dataType: "json",
    error: function(xhr, err) {
    alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
    alert("responseText: " + xhr.responseText);
        },
    success: function() {
        alert("it works" );
        // and here use jQuery to set the control test
        $("#<%=test.ClientID%>".text("Works");
    }
})

I did change the URL for u and if you wanna pass parameters you pass them on Data Section of Ajax method some thing like this 我确实更改了u的URL,如果您想传递参数,可以在Ajax方法的数据部分传递它们,例如:

    '{"fname":"' + fname + '","lname":"' + lname + '","email":"' + email + '","address":"' + 

I wish it helps you address + '"}' 希望它可以帮助您解决+'“}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM