0

I'm using mockjax to simulate an Ajax call, but I'm experiencing that the data received by my Ajax callback is different from what I pass to mockjax (via the 'responseText' parameter). In this example, I've chosen the response to be '14.0', but the callback receives '14' instead:

$.mockjax({
    url: "/test",
    contentType: "text/json",
    responseText: "14.0"
});

$.ajax({
   url: "/test",
   datatype: "json"
}).done(function(data) {
   alert(data);
});​

Why is it that the received data is different from what I specify to responseText? See this fiddle for a working example; a popup dialog will show the string received by the callback, should be '14'.

EDIT:

This is the popup I get when running the fiddle, demonstrating the altered response from mockjax.

fiddle result

Also fixed the fiddle.

aknuds1
  • 65,625
  • 67
  • 195
  • 317

1 Answers1

4

If you change two small things the above snippet will work as you expect.

In the above code snippet the contentType mentioned in $.mockjax is "text/json". In that case the responseText needs to be an object that represents the JSON. https://github.com/appendto/jquery-mockjax

$.mockjax({
    url: "/test",
    contentType: "text/json",
    responseText: { number: 14.0 }
});

Also, in the $.ajax call the datatype key should be dataType http://api.jquery.com/jquery.ajax/

$.ajax({
    url: "/test",
    dataType: "json"
}).done(function(data) {
    console.log(data);
});

I've made the changes in the following jsFiddle http://jsfiddle.net/elijahmanor/BtuW8/

I hope that helps you past the issue.

Elijah Manor
  • 17,923
  • 17
  • 72
  • 79
  • Thanks, it seems wrapping the string in an object (`{number: "14.0"}`) makes all the difference. Do you know why that is? In the real Web service I just return a plain string, but it could be this isn't proper JSON for all I know. – aknuds1 Aug 23 '12 at 19:54
  • It seems if I want a plain string value, I should be using text/plain for content type as opposed to JSON. I guess I learnt something :) – aknuds1 Aug 23 '12 at 19:58
  • 1
    If you wanted to keep it as JSON and keep the .0 then you an put the number in quotes as you did... http://jsfiddle.net/elijahmanor/BtuW8/1/ In JavaScript all numbers are floats. You could have kept the JSON like the above and then formatted the number like this... console.log( data.number.toFixed( 1 ) ) as seen here http://jsfiddle.net/elijahmanor/BtuW8/2/ If you'd like to return valid JSON I would suggest you test it with a validator http://jsonlint.com/ or use a library on your server that exports to JSON – Elijah Manor Aug 23 '12 at 21:52