JQuery返回NaN但并非总是如此

时间:2012-08-13 12:35:59

标签: jquery ajax

我试图将测试的分数传递给php脚本,然后将结果通过电子邮件发送给用户。我正在将分数输出到控制台,效果很好(显示我的百分比),但是当发送电子邮件而不是分数时,它会说NaN。

这是我的代码......

 score = roundReloaded(trueCount / questionLength * 100, 2);

          $.ajax({
                  type: 'POST',
                  url: config.sendResultsURL,
                  data: { q:score },
                  complete: function () {console.log("Sending complete. The score was "+ score + "%");}
                });

我的emailData.php文件......

$body = "You scored " . $_POST['q'] . "%";
$to = "someone@test.com";
$email = 'admin@test.com';

$subject = 'Results';
$headers  = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";

// Send the email:
$sendMail = mail($to, $subject, $body, $headers);

有人可以帮助我并告诉我我做错了什么吗?

由于

2 个答案:

答案 0 :(得分:0)

NaN说这不是一个数字。尝试将$ _POST ['q']转换为如下数字:

$_POST['q']*1

或许这可能是形式方面的问题,请尝试将得分变量转换为字符串:

score = roundReloaded(trueCount / questionLength * 100, 2);

          $.ajax({
                  type: 'POST',
                  url: config.sendResultsURL,
                  data: { q:score+'' },
                  complete: function () {console.log("Sending complete. The score was "+ score + "%");}
                });

编辑:尝试这样做以便更好地记录:

score = roundReloaded(trueCount / questionLength * 100, 2);
var params = {q:score};
console.log(JSON.stringify(params));    
          $.ajax({
                  type: 'POST',
                  url: config.sendResultsURL,
                  data: params,
                  complete: function () {console.log("Sending complete. The score was "+ params.q + "%");}
                });

答案 1 :(得分:0)

如果字符串的第一个字符无法转换为数字。然后返回NaN。

所以这里有转换问题