开发者

How to execute a function inside json property?

I return this json from the server:

{
    "Id": 0,
    "Name": ko.observable('New Product'),
    "PurchasePrice": 0.0,
    "DownPayment": 0.0,
    "TotalPayment": 0.0,
    "MortgageInsurance": 0.0,
    "PurchaseOrRefinance": null,
    "Client": null,
    "MonthlyCosts": null,
    "ClosingCosts": null,
    "FirstLien": null,
    "SecondLien": null
}

I retrieve it using jQuery.getJson like this:

function addProduct(){
    $.getJSON('@Url.Action("GetNewProduct","Product")',function(data){
        viewModel.products.push(data);
    });
    viewModel.productSaved(false);
    viewModel.product(products[products.length - 1]);

}

However, it seems as if the code never runs. This only happends when 开发者_运维百科I return the function in the json, if I remove the function everything runs fine. Is there a way to work this out?


It should be like this >

Return this

{"Id":0,"Name":'New Product',"PurchasePrice":0.0,"DownPayment":0.0,"TotalPayment":0.0,"MortgageInsurance":0.0,"PurchaseOrRefinance":null,"Client":null,"MonthlyCosts":null,"ClosingCosts":null,"FirstLien":null,"SecondLien":null}

and make it like this >

    function addProduct(){
        $.getJSON('@Url.Action("GetNewProduct","Product")',function(data){
            data.Name = ko.observable(data.Name);  
            viewModel.products.push(data);
        });
        viewModel.productSaved(false);
        viewModel.product(products[products.length - 1]);

    }


Parsing your data fails since

{"Name":ko.observable('New Product') }

isn't actually JSON. You can pass only basic data such as strings/numbers/objects via JSON. See http://www.json.org/

You may consider calling jQuery.ajax() with dataType set to 'script'.

Otherwise you need to initialize your variables within your callback function or in the server code, which might even be a cleaner aproach.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜