user1473094
user1473094

Reputation: 41

Simplest way to test ASP.NET Webservice that returns JSON from some JavaScript?

We have a .asmx service that returns JSON data. Can someone point me to a simple example that calls the service from a page w JavaScript ? Tks

Upvotes: 4

Views: 381

Answers (1)

David East
David East

Reputation: 32604

You can use jQuery's get function.

var dataID = $('#WhatINeedForAParameter').val();
$.get('WebApiAddress/MethodName', { id: dataID }, 
   function(data) {
     alert(data);
     // Since your method returns a JSON object you can access
     // the properties of that object
     alert(data.id);
     alert(data.name);
});

Or if you want to use the long hand jQuery ajax you can do the following:

var dataID = $("#WhatINeedForAParameter").val();
var request = $.ajax({
  url: "WebApiAddress/MethodName",
  type: "POST",
  data: { id : dataID },
  dataType: "jsonp"
});

request.done(function(msg) {
  alert('You got this ' + msg);
});

request.fail(function(jqXHR, textStatus) {
  alert( "Your request failed: " + textStatus );
});

Upvotes: 5

Related Questions