简单的Ajax调用不工作按一下按钮按钮、简单、工作、Ajax

2023-09-10 17:40:05 作者:当你听我说

我使用 Encosia的样本从他的网站上如何使用Ajax调用

在我的DIV点击它的正常工作,当我更换,而不是DIV按钮它刷新整个页面,我没有发现任何错误的萤火。

下面是我的code:

脚本:

 <脚本类型=文/ JavaScript的>
    $(文件)。就绪(函数(){
        //添加页面的方法调用作为一个onclick处理程序分区。
        $(#GETDATE)。点击(函数(){
            $阿贾克斯({
                键入:POST,
                网址:Default.aspx的/ GETDATE
                数据: {},
                的contentType:应用/ JSON的;字符集= UTF-8,
                数据类型:JSON,
                成功:函数(MSG){
                    //替换div的内容与页面方法的返回。
                    $(#结果)HTML(msg.d);
                }
            });
        });
    });
< / SCRIPT>
 
jquery ajax get怎么用

HTML:

 < ASP:ScriptManager的ID =ScriptManager1=服务器的EnablePageMethods =真>
< / ASP:ScriptManager的>
< D​​IV ID =结果>点击此处查看时间< / DIV>
<按钮ID =GETDATE值=点击我> ClickMe< /按钮>
 

code-背后:

 <的WebMethod()> _
< ScriptMethod(ResponseFormat:= ResponseFormat.Json)>
公共共享功能GETDATE()作为字符串
     返回DateTime.Now.ToString()
端功能
 

解决方案

什么最有可能发生的是 - 该按钮提交页面使页面被重新加载。我以前在一些浏览器有这个问题。 您需要指定 TYPE =按钮属性。

http://www.w3schools.com/tags/tag_button.asp

I am using Encosia's sample from his website on how to use ajax call

When I click on the div it's working fine and when I replace button instead of div it's refreshing the whole page and I don't find any errors in firebug.

Here is my code:

Script:

<script type="text/javascript">
    $(document).ready(function () {
        // Add the page method call as an onclick handler for the div.
        $("#getdate").click(function () {
            $.ajax({
                type: "POST",
                url: "Default.aspx/GetDate",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    // Replace the div's content with the page method's return.
                    $("#Result").html(msg.d);
                }
            });
        });
    });
</script>

HTML:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
<div id="Result">Click here for the time.</div>
<button id="getdate" value="Click Me">ClickMe</button>

Code-behind:

<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Shared Function GetDate() As String
     Return DateTime.Now.ToString()
End Function

解决方案

What most probably happens is - the button submits the page so the pages gets reloaded. I had this problem before in some browsers. You need to specify type="button" attribute.

http://www.w3schools.com/tags/tag_button.asp