日期:2014-05-17  浏览次数:20411 次

AJAX 客户端使用JS调用页面中的类方法?
页面中的脚本如下:
JScript code

function btnInvoke_onclick()
{
    var theName = document.getElementById("tbName").value;
    PageMethods.SayHelloFromPage(theName, onSayHelloSucceeded);
}

function onSayHelloSucceeded( result )
{
    document.getElementById("resultDiv").innerText = result;
    //document.getElementById("resultDiv").innerHtml = result;

}



aspx页面文件:
HTML code

<from id="form1" runat="server">
    <asp:ScriptManager ID="sm" EnablePateMethods="true" runat="server">
    </asp:ScriptManager>
    <div>
    <input id="tbName" type="text" runat="server" />
    <input id="btnInvoke" type="button" value="Say Hello"  runat="server" onclick="return btnInvoke_onclick()
" />
    <div id="resultDiv" runat="server" style="border:solid 2px blue;">
    </div> 
    <div>
</from>



CS文件:
C# code

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

[WebMethod]
public static string SayHelloFromPage( string name )
{
    return string.Format("Hello {0}!", name);
}



出现下面的错误:
在文本框中输入任意字符,
第一次点击“Say Hello”按钮后,出现对话框,内容为:“The server method 'SayHelloFromPage' failed with the follow error:”,后面的内容看不到。
第二次点击“Say Hello”按钮后,在页面的resultDiv中出现了“当前页面的html内容”。

该程序是从网上的某个博客中找到的,据博主所说,内容出自“APS.NET AJAX 程序设计”。
程序我稍微做了一点修改:我把客户端的控件全部设置为了服务器端控件,其他没有变化。这样改动的原因是,源程序调试时报错。

请教错误的原因,谢谢!


------解决方案--------------------
可能是两方面的原因

一,scriptmanager或proxy内要有webservice的地址
C# code

<asp:ScriptManagerProxy ID="scriptProxy" runat="server">
        <Services>
            <asp:ServiceReference Path="~/Portal/HomePageSetting.asmx" />
        </Services>
    </asp:ScriptManagerProxy>

------解决方案--------------------
先“规范地”按照msdn演练一下简单范例:http://msdn.microsoft.com/zh-cn/library/bb532367(v=vs.90).aspx
如果这个就直接出错,查看你的环境是否错误,就不用管技术方法本身是否写对了。
------解决方案--------------------
js直接调用asp.net服务器方法参见:
http://msdn.microsoft.com/en-us/library/ms178210(v=vs.100).aspx

注意到楼主最近一系列提问,建议楼主还是系统了解一下微软的jsAPI,
这里囊括了所有js调用webservice,wcf,httpreq,
以及本贴你关注的js调用服务器方法的知识:
http://msdn.microsoft.com/en-us/library/bb310860(v=vs.100).aspx