Create Rich Web Apps with AJAX: Listing 3: C#, Process Results from a Web Service

ASP.NET AJAX-enabled Web services can be called directly using JavaScript. This example shows how to call the Web service shown in <a href="http://visualstudiomagazine.com/listings/list.aspx?id=185" target="_blank">Listing 2</a> and process the results. All books returned by the Web service are added to the page using the browser's document object model.

function SearchBooks()
{
      var amazonDiv = $get("divAmazon");
      amazonDiv.innerHTML = "Loading Books";
      currPage++;

      //Call Web Service using client-side proxy object
      GolfClubShack.AmazonService.GetBooks("Golf",
           currPage,OnWSCallback);
}

function OnWSCallback(results)
{
       var amazonDiv = $get("divAmazon");
       if (results == null || results == "undefined" || 
           results.length == 0)
       {
           amazonDiv.innerHTML = "No books found";
           return;
        }

        amazonDiv.innerHTML = "";
        for (var i=0;i<results.length;i++)
        {
           var book = results[i];
           var bookDiv = document.createElement("div");
           bookDiv.style.width = "100%";
           bookDiv.style.clear = "both";
           bookDiv.style.paddingTop = "10px";
           bookDiv.setAttribute("url",book.URL);
           //Add href to amazon.com when div is clicked
        $addHandler(bookDiv,"click",NavigateToAmazon);

           //Image
           var imgDiv = document.createElement("div");
           imgDiv.style.width = "65px";
           if (document.all) imgDiv.style.styleFloat = "left";
           else imgDiv.style.cssFloat = "left";
           var bookImg = document.createElement("img");
           bookImg.src = book.ImageURL;
           imgDiv.appendChild(bookImg);
           bookDiv.appendChild(imgDiv);

           var detailsDiv = document.createElement("div");
           if (document.all) 
                detailsDiv.style.styleFloat = "left";
           else 
                detailsDiv.cssFloat = "left";

           //Title
           var bookTitle = document.createElement("div");
           bookTitle.className = "blackTextSmall";
           bookTitle.innerHTML = book.Title;
           detailsDiv.appendChild(bookTitle);

           //Price
           var bookPrice = document.createElement("div");
           bookPrice.className = "blackTextSmall";
           bookPrice.innerHTML = book.Price;
           detailsDiv.appendChild(bookPrice);
           bookDiv.appendChild(detailsDiv);

           //Add to container div
           amazonDiv.appendChild(bookDiv);
      
      amazonDiv.appendChild(document.createElement("br"));
      }

}
comments powered by Disqus

Featured

Subscribe on YouTube