I’ve seen the following example in the web to get a Json Product object into js from a WCF service:
function Product(ProductName, ProductDesc, Price, Quantity) {
this.ProductName = ProductName;
this.ProductDesc = ProductDesc;
this.Price = Price;
this.Quantity = Quantity;
}
function CallWCFService(WCFServiceURL) {
$.ajax({
type: "GET",
url: WCFServiceURL,
contentType: "application/json; charset=utf-8",
dataType: 'json',
processdata: true,
success: function (msg) {
WCFServiceSucceeded(msg);
},
error: WCFServiceFailed
});
}
//On Successful WCF Service call
function WCFServiceSucceeded(result) {
var productsArray = new Array();
//Gets the Products
$.each(result, function (i, Product) {
productsArray[i]=Product;
});
//Print all the product details
$.each(productsArray,function(i,Product)
{
alert(Product.ProductName + ' ' + Product.ProductDesc + ' ' + Product.Price + ' ' + Product.Quantity)
});
}
Now, i cannot say what is really supposed to happen in here (my knowledge in javascript and jquery is scarily small), but i can say that i want to understand this snippet, in order to be able to modify it in order to contain a nested type, i.e: instead of ProductName we’ll have a list property from the WCF service response with its own fields.
Now, concretely, in this example, i don’t understand where is the Product function being called, it would seem to be that it is in here:
//Gets the Products
$.each(result, function (i, Product) {
productsArray[i]=Product;
});
but to me it seems that is not clear if Product is there behaving as a declared parameter of the lambda that is being passed to $.each or if its actually invoking the ‘constructor’ call
Can you enlighten me on this code?
The
Productfunction is never called. In fact, the code works perfectly fine without it. What’s happening is the JSON objects returned by the WCF call are in the exact same format or structure as theProductclass (defined by theProductfunction).The
eachfunction takes an array and for each item in the array it executes the anonymous function supplied. The anonymous function has two parameters,iandProduct.iis the index of the item in the array.Productis the name of the variable for the item passed in. At this point, the variable namedProducthas shadowed theProductfunction.The reason it appears that the items have been converted to a
Productclass is because the objects have the same structure.