开发者

Calling service from Html

i want to call asp.net web service from java script and pass the parameters to it .is there any code sample or demostration that will help me to ach开发者_如何学编程eive that?? thanks in advance


JQuery:

function AddLocation(ParentID) {
    $.ajax({
        type: "POST",
        url: "../server.asmx/Save",
        data: "{'ID':'0','ParentID':'" + ParentID + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            var item = document.createElement('option');
            item.value = data.d.split("$")[0];
            item.text = name;
            //do stuff
        }
    });
}


jQuery supports this behavior. you can use jQuery to do the ajax call as show below. this method has two call back functions for success and for failure.

function loadData()
{
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: 'methodurl',
        success: methodSuccedded,
        error: methodFailure
    });
}

function methodSuccedded()
{
    //do your logic.
}

function methodFailure()
{
    //do your logic.
}


You can do so, using AJAX, and get the response from the server as an JSON object.

    var xmlHttp = new ActiveXObject("Microsoft.XmlHttp");
    var url = "Service1.svc/ajaxEndpoint/";
    url = url + "Sum2Integers";
    var body = '{"n1":';
    body = body + document.getElementById("num1").value + ',"n2":';
    body = body + document.getElementById("num2").value + '}';

    // Send the HTTP request
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/json");
    xmlHttp.send(body);

    // Create result handler 
    xmlHttp.onreadystatechange= function X()
    {

         if(xmlHttp.readyState == 4)
         {
              result.innerText = xmlHttp.responseText;
         }
    }

Getting the response as JSON would help you evualte it asn object and u can act on it through JavaScript.

See these links for reference: http://blogs.msdn.com/b/alikl/archive/2008/02/18/how-to-consume-wcf-using-ajax-without-asp-net.aspx

http://dotnetslackers.com/articles/ajax/JSON-EnabledWCFServicesInASPNET35.aspx


The below link is a pretty decent method from my experience.

http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜