简体   繁体   English

ASP.NET jQuery Ajax 调用代码隐藏方法

[英]ASP.NET jQuery Ajax Calling Code-Behind Method

I am very new to web development, but have a lot of experience in development in general.我对 Web 开发陌生,但总体上有很多开发经验。 I have an ASP page that has a few input fields and a submit button.我有一个 ASP 页面,它有几个输入字段和一个提交按钮。 This submit button purely calls $.ajax, which I intended to have call a method in the code-behind file.这个提交按钮纯粹调用 $.ajax,我打算调用代码隐藏文件中的一个方法。 However, I've noticed two interesting things.但是,我注意到了两件有趣的事情。 First, the ajax call succeeds regardless of what data is provided to it.首先,无论提供给它什么数据,ajax 调用都会成功。 Secondly, the responseText field is the entire page's html source.其次, responseText 字段是整个页面的 html 源。

I've read this and other articles that point to the webconfig, but these solutions do not seem to resolve my issue.我已经阅读了这篇文章和其他指向 webconfig 的文章,但这些解决方案似乎并没有解决我的问题。

Here is the asp page:这是asp页面:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="TesScript.js"></script>
    <link rel="Stylesheet" type="text/css" href="TestStyle.css" />
</head>
<body>
    <div>
        <ul class="tempList">
            <li>Name:
                <input id="nameText" type="text" />
            </li>
            <li>Attending:
                <input id="yesButton" type="radio" name="attending" />
                Yes
                <input id="noButton" type="radio" name="attending" />
                No </li>
            <li>Return Address:
                <input id="returnAddressText" type="text" />
            </li>
            <li>
                <input id="submitButton" type="button" onclick="submit()" value="Submit" />
            </li>
        </ul>
    </div>
    <ul id="errorContainer" class="errorSection" runat="server" />
    <ul id="messageContainer" class="messageSection" runat="server" />
</body>
</html>

The code behind:背后的代码:

using System;
using System.Web.Services;
using System.Web.UI;

namespace TestAspStuff
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }


        [WebMethod]
        public static string OnSubmit(string name, bool isGoing, string returnAddress)
        {
            return "it worked";
        }
    }
}

And the JavaScript:和 JavaScript:

function submit() {

    var name = "my name";
    var isAttending = true;
    var returnAddress = "myEmail@gmail.com";

    SendMail(name, isAttending, returnAddress);
}

function SendMail(person, isAttending, returnEmail) {

    var dataValue = { "name": person, "isGoing": isAttending, "returnAddress": returnEmail };

    $.ajax({
        type: "POST",
        url: "Default.aspx/OnSubmit",
        data: dataValue,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        complete: function (jqXHR, status) {
            alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
        }
    });

}

Now, I noticed I can change the url property to anything I want and the error method is never called, and the status is success, with the responseText being the entire html page.现在,我注意到我可以将 url 属性更改为我想要的任何内容,并且永远不会调用错误方法,并且状态为成功,responseText 是整个 html 页面。 My webconfig has all of the appropriate sections (including the htmlModule section).我的 webconfig 具有所有适当的部分(包括 htmlModule 部分)。 I am working in .Net 3.5.我在 .Net 3.5 中工作。 I appreciate any help and, again, I'm really new to this so what's obvious to others is most likely not obvious to me.我感谢任何帮助,同样,我对此很陌生,因此对其他人显而易见的事情对我来说很可能并不明显。 And if there's a better way to do this (calling asp.net code-behind methods from JavaScript, that is) please feel free to post that.如果有更好的方法来做到这一点(即从 JavaScript 调用 asp.net 代码隐藏方法),请随时发布。 Thanks!!!谢谢!!!

Firstly, you probably want to add a return false;首先,您可能想要添加一个 return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).到 JavaScript 中 Submit() 方法的底部(因此它停止提交,因为您在 AJAX 中处理它)。

You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected.您正在连接到完整事件,而不是成功事件 - 存在显着差异,这就是您的调试结果不符合预期的原因。 Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType.另外,我从来没有让签名方法与你的相匹配,而且我总是提供一个 contentType 和 dataType。 For example:例如:

$.ajax({
        type: "POST",
        url: "Default.aspx/OnSubmit",
        data: dataValue,                
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        success: function (result) {
            alert("We returned: " + result);
        }
    });

This hasn't solved my problem too, so I changed the parameters slightly.这也没有解决我的问题,所以我稍微改变了参数。
This code worked for me:这段代码对我有用:

var dataValue = "{ name: 'person', isGoing: 'true', returnAddress: 'returnEmail' }";

$.ajax({
    type: "POST",
    url: "Default.aspx/OnSubmit",
    data: dataValue,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    success: function (result) {
        alert("We returned: " + result.d);
    }
});

I know it's an old thread.我知道这是一个旧线程。 One possible solution is to use JSON.stringify( ) to convert it to a proper JSON string.一种可能的解决方案是使用JSON.stringify( )将其转换为正确的 JSON 字符串。 This will resolve any data parameter values related issue.这将解决任何与数据参数值相关的问题。

function SendMail(person, isAttending, returnEmail) {

    var dataValue = { "name": person, "isGoing": isAttending, "returnAddress": returnEmail };

    $.ajax({
        type: "POST",
        url: "Default.aspx/OnSubmit",
        data: JSON.stringify(dataValue),
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        complete: function (jqXHR, status) {
            alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
        }
    });

}

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

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