I have the following jQuery that sets the content of each (empty) DIV (with unique id’s that start with alpha characters) that has a class = ‘editable’. I’m using an MVC4 api controller with a GET method to return a string of HTML.
For some reason the loadStuff function below is outputting quotes that can be seen in the web page before and after the returned content. This happens on every DIV and is definitely not returned in the api controller method returning a string.
$(document).ready(function () {
$('.editable').each(function () {
var curId = this.id.replace('content', '');
loadStuff(curId, this.id);
})
});
function loadStuff(curId, targetId) {
$('#' + targetId).load('api/briefingItem/' + curId);
}
However when I replace the loadStuff function with the code below and use .appendTo the quotes don’t appear.
function loadStuff(curId, targetId) {
$.getJSON("api/briefingItem/" + curId,
function (data) {
$(data).appendTo('#' + targetId);
})
}
This seems overkill for returning a simple string and documentation suggests. Can anyone explain this unusual behaviour?
API Controller
// GET api/BriefingItem/5
public string Get(int id)
{
string newVal = string.Empty;
switch (id)
{
case 12:
newVal = @"<p>this is some example text that you can edit inside the <strong>tinymce editor</strong>.</p><p>nam nisi elit, cursus in rhoncus sit amet, pulvinar laoreet leo. nam sed lectus quam, ut sagittis tellus. quisque dignissim mauris a augue rutrum tempor. donec vitae purus nec massa vestibulum ornare sit amet id tellus. nunc quam mauris, fermentum nec lacinia eget, sollicitudin nec ante. aliquam molestie volutpat dapibus. nunc interdum viverra sodales. morbi laoreet pulvinar gravida. quisque ut turpis sagittis nunc accumsan vehicula. duis elementum congue ultrices. cras faucibus feugiat arcu quis lacinia. in hac habitasse platea dictumst. pellentesque fermentum magna sit amet tellus varius ullamcorper. vestibulum at urna augue, eget varius neque. fusce facilisis venenatis dapibus. integer non sem at arcu euismod tempor nec sed nisl. morbi ultricies, mauris ut ultricies adipiscing, felis odio condimentum massa, et luctus est nunc nec eros.</p>";
break;
case 13:
newVal = @"<p>look up $(content).load() jquery method and the callback function.</p>";
break;
default:
newVal = @"<h3>click to enter content.</h3>";
break;
}
return newVal;
}
The actual response from the Web API is a string which is enclosed in double quotes.
The difference between the
$.getJSON()and.load()methods is that the$.getJSONmethod assumes that the response is a JSON encoded string => it strips the double quotes wheres .load assumes HTML and doesn’t do any processing on the result.So you could have your Web API controller action return a
text/htmlinstead ofapplication/jsonencoded request:Now you could use the
.load()method but not the$.getJSONmethod.