javascript无法从网络方法中获取价值。
对于位于CallMe()中的s值,它表示未定义。
我的目标是从Web方法获取一个对象....使用js中的数据..
我缺少什么_?
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Script.Services;
public partial class _Default : System.Web.UI.Page
{
Label lblGeneral;
protected void Page_Load(object sender, EventArgs e)
{
lblGeneral = textMessager;
}
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ShowMessage()
{
return ExternalManager.Write();
}
}
JS
// JScript File
function CallMe()
{
// call server side method
var s = PageMethods.ShowMessage();
s = eval(s);
}
(function() {
var status = true;
var fetchService = function() {
if(status){
CallMe();
status = false;
}
setTimeout(fetchService, 5000);
status = true;
}
window.onload = fetchService;
}())
**** Util类******
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
/// <summary>
/// Summary description for ExternalManager
/// </summary>
public class ExternalManager
{
public ExternalManager()
{
//
// TODO: Add constructor logic here
//
}
public static string Write()
{
string s = "Okay Buddy" + DateTime.Today.ToLongDateString();
JavaScriptSerializer jss = new JavaScriptSerializer();
string serializedPerson = jss.Serialize(s);
return s;
}
}
二手技术: 启用了Asp.net 2.0 + Ajax C#
答案 0 :(得分:1)
这是一个AJAX电话。你不能写:
var s = PageMethods.ShowMessage();
并期望立即使用s
变量,因为调用是异步的(它会立即返回,但结果仅在服务器响应后才可用)。您需要使用回调。这是一个完整的工作示例:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>
<%@ Import Namespace="System.Web.Script.Services" %>
<script type="text/C#" runat="server">
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ShowMessage()
{
return "Okay Buddy" + DateTime.Today.ToLongDateString();
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function CallMe() {
// call server side method
PageMethods.ShowMessage(function (result) {
alert(result);
});
}
(function() {
var status = true;
var fetchService = function () {
if (status) {
CallMe();
status = false;
}
setTimeout(fetchService, 5000);
status = true;
}
window.onload = fetchService;
}());
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" />
</form>
</body>
</html>
另请注意,您不应手动使用JavaScriptSerializer
。它由PageMethods
内部使用。在ShowMessage
方法中,您还可以返回复杂对象。
如果方法有两个参数,你可以在成功和错误回调之前传递它们:
PageMethods.ShowMessage('param1', 'param2', onSucceed, onError);