代码之家  ›  专栏  ›  技术社区  ›  Jalpesh Vadgama

如何从javascript调用C#Rest Web服务

  •  0
  • Jalpesh Vadgama  · 技术社区  · 15 年前

    我已经在C#中创建了一个基于rest架构的web服务,它将返回一个json字符串。我想从javascript访问这个web服务,如何从javascript调用这个web服务。

    2 回复  |  直到 15 年前
        1
  •  0
  •   Andy E    15 年前

    XMLHttpRequest 对象(或基于COM的brother):

    function getJSON()
    {
        var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
        xhr.open("GET", "http://mysite.com/myscript.asp", true);
        xhr.onreadystatechange = function ()
        {
            if (xhr.status == 200 && xhr.readystate == 4)
            {
                if (JSON) // provided by json2.js or browsers with native JSON
                    var result = JSON.parse(xhr.responseText);
                else
                    var result = eval ('(' + xhr.responseText + ')');
    
                // Do something with the result here
            }
        }
        xhr.send();
    }
    

    http://www.json.org/js.html