Why does mockjax return an altered response to my Ajax consumer?
Asked Answered
C

1

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.

Coridon answered 23/8, 2012 at 14:16 Comment(0)
A
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.

Amena answered 23/8, 2012 at 19:35 Comment(3)
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.Coridon
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 :)Coridon
If you wanted to keep it as JSON and keep the .0 then you an put the number in quotes as you did... 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 jsfiddle.net/elijahmanor/BtuW8/2 If you'd like to return valid JSON I would suggest you test it with a validator jsonlint.com or use a library on your server that exports to JSONAmena

© 2022 - 2024 — McMap. All rights reserved.