JSON Response {"d":"128.00"} but displaying "128"
I have been working on a shopping cart that the user can add/remove order items as they please and am returning an updated sub-total via a webservice using jQuery $.ajax
Here is how I am calling the webservice and setting the sub-total with the response.
//perform the ajax call
$.ajax({
url: p,
data: '{' + s + '}'开发者_如何学Go,
success: function(sTotal) {
//order was updated: set span to new sub-total
$("#cartRow" + orderID).find(".subTotal").text(sTotal);
},
failure: function() {
//if the orer was not saved
//console.log('Error: Order not deleted');
}
});
The response I am getting seems perfectly fine:
{"d":"128.00"}
When I display the total on the page it displays as 128 rather than 128.00
I am fully sure it is something very simple and silly but I am so deep into it now I need someone with a fresh brain to help me out!!
Cheers :)
EDIT
I am also using $.ajaxSetup to set the correct contentType:
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data) {
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
}
});
That is because the value is treated as a number, while you want it treated as a string. When you are using '.. .text(sTotal)', you are actually calling the .toString() method on the Number object wrapping the primitive sTotal. And since this is a whole number, it displays it without decimals. You need to use a format the number as a string prior to calling .text(foo) for the number to be formatted like that.
This will give you two decimals
var a=1/3;
a = a.toString();
switch(a.lastIndexOf(".")){
case -1:
a+=".00";
break;
case a.length-2:
a+="0";
break;
default:
a=a.substring(0, a.indexOf(".") + 3);
}
alert(a);
I don't see anywhere in this code where you access the d
property of the response.
Perhaps you mean to do this?
$("#cartRow" + orderID).find(".subTotal").text(sTotal.d);
// --------------------------------------------------^^
EDIT
Ok, I see the problem. You're returning JSON but not defining a dataType in the $.ajax()
call. This means that jQuery sees your application/json
mimetype and interprets the response as JSON. 128.00
in JSON is a Number, not a String. However, "128.00"
would be a String.
In order to keep this working, You need to format the response before printing it (as others have suggested), or adjust your endpoint to return a valid JSON string.
Here's my test to prove the solution
<div id="test">
Subtotal <span class="subTotal"></span>
</div>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" charset="utf-8">
google.load("jquery", "1.4.2");
</script>
<script type="text/javascript" charset="utf-8">
$.ajax({
url: 'test.php',
data: {},
success: function(sTotal) {
//order was updated: set span to new sub-total
$("#test").find(".subTotal").text(sTotal);
}
});
</script>
and test.php
<?php
header( 'Content-type: application/json' );
echo '128.00';
Output
Subtotal 128
But when I change test.php to be this
<?php
header( 'Content-type: application/json' );
echo '"128.00"';
The expected output is generated
Subtotal 128.00
Or, you could alternatively tell jQuery to treat the response as text by specifying a dataType parameter, for example
$.ajax({
url: 'test.php',
data: {},
dataType: 'text', // <---- here
success: function(sTotal) {
//order was updated: set span to new sub-total
$("#test").find(".subTotal").text(sTotal);
}
});
EDIT 2
Ok, after messing with this some more, I see what's going on. The dataFilter handler you defined converts the response into JSON itself, and in this case, returns the string 128.00
. However, jQuery still applies the intellgent-guessed dataType (which is JSON) to this value before sending it to the success handler.
There are a multitude of ways to fix this, all of which depend on what other AJAX calls your application relies on this setup for. The quick-fix I applied in my test was to do this
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
// define the text data type so that we return data.d, jQuery doesn't parse it as JSON again
dataType: 'text',
dataFilter: function(data) {
data = $.parseJSON( data ); // Use jQuery's parsing
if (data.hasOwnProperty('d'))
{
return data.d;
}else{
return data;
}
}
});
But that may not work across the board for you
Please try this:
$("#cartRow" + orderID).find(".subTotal").text(sTotal.toFixed(2));
HTH
精彩评论