js調用CS裡的方法有很多,我用一種簡單的方法,如下
CS裡
public string test()
{
return "Hello World";
}
public string test()
{
return "Hello World";
}
aspx 頁面
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>無標題頁</title>
<mce:script type="text/javascript" ><!--
var demo=function(){
var b= "<%=test() %>";
alert(b);
}
// --></mce:script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="id1" onclick="demo()" value="JS調用CS" />
</div>
</form>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>無標題頁</title>
<mce:script type="text/javascript" ><!--
var demo=function(){
var b= "<%=test() %>";
alert(b);
}
// --></mce:script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="id1" onclick="demo()" value="JS調用CS" />
</div>
</form>
</body>
</html>
上面的是不帶參數的,要是後台CS裡方法帶參數就要注意了。。
CS:
public string test(string a)
{
return a;
}
[c-sharp] view plaincopy
public string test(string a)
{
return a;
}
aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>無標題頁</title>
<mce:script type="text/javascript" ><!--
var demo=function(){
var a="Hello World";
var b= '<%=test("'+a+'") %>';//這裡一定注意單引號和雙引號的使用!!!!!
alert(b);
}
// --></mce:script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="id1" onclick="demo()" value="JS調用CS" />
</div>
</form>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>無標題頁</title>
<mce:script type="text/javascript" ><!--
var demo=function(){
var a="Hello World";
var b= '<%=test("'+a+'") %>';//這裡一定注意單引號和雙引號的使用!!!!!
alert(b);
}
// --></mce:script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="id1" onclick="demo()" value="JS調用CS" />
</div>
</form>
</body>
</html>
帶參數的調用'<%=test("'+a+'") %>' 一定要用單引號包起'<%=%>',裡面再是雙引號。這點是關鍵,否則
調用不成功!