Question

I am returning JSON from an AJAX service and binding the results using KnockoutJS.

One of my bindings is an image, and I need part of the URL to come from the ViewModel like so: https://graph.facebook.com/' + facebookPageID + '/picture?type=large' }" />

If you copy and paste the result of the constructed image tag it gives a valid image from a facebook page. But when bound into the src attribute it seems to strip non alpha-numeric characters from the path.

Here is a JSFiddle of my problem http://jsfiddle.net/8rb8v/1/

Here is the HTML:

<h1>Events</h1>
<button id="btnSearch">Click to Search</button>
<div class="myresult" data-bind="foreach: events">
    <div>
        Name: <span data-bind="html: Name"></span><br/>
        facebookPageID: <span data-bind="html: facebookPageID"></span><br/>
        Constructed Image Tag: <span data-bind="html: 'https://graph.facebook.com/' + facebookPageID + '/picture?type=large'"></span><br/>
        <img width=100 height=100 border=1 data-bind "attr:{ src: 'https://graph.facebook.com/' + facebookPageID + '/picture?type=large' }" />
    </div>
</div>

Here is the code:

var jsonData = {
        "events": [{
            "Name": "London marathon",
            "facebookPageID": "71506449747"
        }, {
            "Name": "Great North Run",
            "facebookPageID": "71506449747"
        }]
    };

// View model declaration
var EvViewModel = {
    events: ko.observableArray([])
};

function getEvents() {
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/echo/json/',
        data: { json: JSON.stringify(jsonData) },
        success: function (data) {
            EvViewModel.events(data.events);
            $("myresult").fadeIn();
        },
    });
}

$(document).ready(function () {
    $('#btnSearch').click(getEvents);
    ko.applyBindings(EvViewModel);
});

Thanks

Was it helpful?

Solution

Your markup is invalid:

<img width=100 height=100 border=1 data-bind "attr:{ src:
                                            ^
                                            missing an equals sign

It may be possible that the browser is trying to turn the data-bind attribute value into part of an attribute name, thus stripping out the non-alphanumeric characters.

Also, you should always use quotation marks around your attribute values:

<img width="100" height="100" border="1" data-bind="..." />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top