实例化从发出GET请求接收到的值

本文关键字:请求 GET 实例化 | 更新日期: 2023-09-27 18:18:44

我有这个JS代码,它将接收字符串值,从c#代码

function getMsg() {
var xmlhttp = new XMLHttpRequest(); 
xmlhttp.open("GET", "andSert.asmx/GetMessage", true); //async
var temp = the string I receive from the GET above
return temp;

}

下面是c#代码
[WebMethod]
public string GetMessage() {
    XmlTextReader reader = new XmlTextReader (Global.sAppPath + "/alt/importantMsg.xml");
    string message = null;
    while (reader.Read()) {
        if (reader.IsStartElement ()) {
            switch (reader.Name.ToString ()) {
            case "Message":
                message = reader.ReadString();
                break;
            }
        }
    }
    return message;
}

我的问题是,我不知道如何实例化我从做一个get请求在JS代码的消息。我已经测试了一切工作,并返回一个字符串。但是我需要实例化这个字符串,这样我就可以在另一个JS文件中使用它。

我该怎么做?

实例化从发出GET请求接收到的值

您可以考虑使用jQuery $。而不是Ajax,因为它可以保护您免受浏览器怪癖的影响。

同步解决方案:

function getMsg() {
  var msg = "";
  xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    { 
      msg = JSON.parse(xmlhttp.responseText).d;
    }
  };
  xmlhttp.open("GET","andSert.asmx/GetMessage",false);
  xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  xmlhttp.send();
  return msg;
}

异步解决方案:

function getMsg(fCallback) {
  var msg = "";
  xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      fCallback(JSON.parse(xmlhttp.responseText).d);
    }
  };
  xmlhttp.open("GET","andSert.asmx/GetMessage",true);
  xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  xmlhttp.send();
}
getMsg(function(message) { alert(message); });

还必须适当地装饰服务:

using System.Web.Script.Services;
using System.Web.Services;
namespace Whatever {
  [WebService(Namespace = "http://tempuri.org/")]
  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  [System.ComponentModel.ToolboxItem(false)]
  [ScriptService]
  public class andSert : System.Web.Services.WebService {
    [ScriptMethod(UseHttpGet = true)]
    [WebMethod]
    public string GetMessage() {
      return "Hello World";
    }
  }
}

注意类的名称应该像class MyFavouriteClass,使用class andSert来匹配你的问题。