开发者

Getting a single numeric value from MySQL using jQuery and PHP with refusal to behave as int at js level

I have a MySQL database with a column of numeric value. When I query this database in PHP and echo the mysql_result back to jQuery, the values returned appear to have superfluous line breaks and spaces (according to Firebug and experiments with alert()).

The resultant variable appears to work as I had expected when placed into an element with innerhtml, but I can't get logical or mathematical functions to work with it, even after attempting to clear out any of the extra characters and runn开发者_Go百科ing parseInt...

Some sample code is below, but I'm probably doing something quite simple wrong.

Any ideas?

PHP "loadxp.php"

<?php session_start();

include("dbconnect.php");
//retrieve userid from session variable
$user =  $_SESSION['userid']; 
$query = "SELECT xp FROM breadusers WHERE userid='$user'";
$link =@mysql_query($query);
if(!$link){
    die('Could not query:' . mysql_error());
}   
echo mysql_result($link, 0);
?>

Javascript:

function showXP(){
                var xP;
                var level;
                //jQuery AJAX load XP
                $.get("scripts/loadxp.php", function(data){
                    xP = data;
                    //Display XP
                    $('#xpDisplay').html(xP);//NB: WORKS AS EXPECTED
                    //Calculate level
                    level = calculateLevel(xP);
                    //Display level
                    $('#levelDisplay').html(level);//Always NaN
                });
            }

function calculateLevel(xP){
                var level;
                var xPInt;
                xP = xP.replace(/(\r\n|\n|\r| )/gm,"");//Attempt to strip out line breaks and spaces
                xPInt = parseInt(xP,10);//Always seems to return "NaN"
                alert("xP value: \"" + xP + "\"  of type: " + typeof(xP) + "\nxPInt value: \"" + xPInt + "\"  of type: " + typeof(xPInt));//xP is described as String "0", xPInt Number "NaN"
                if ( xP == 0 ) {
                    level = 1;
                } else {
                    level = Math.floor(1+Math.sqrt((xP/125) + 1));
                }
                return level;
            }


Short answer: use JSON. PHP:

$xp = (int)mysql_result($link, 0);
echo json_encode($xp);

JavaScript:

$.getJSON('scripts/loadxp.php', function(xp) {
  alert(xp);         // 1
  alert(typeof xp);  // number
});

It's worth noting that you can send any number of native types back and forth using JSON. Strings, numbers, booleans, null, arrays, and objects are all supported.


I notice you are missing quotes around the first value in the xP.replace() line, that might be the reason it doesn't work in JS.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜