javascript - AJAX 返回的字符串未验证

标签 javascript php ajax

我通过 AJAX 将“true”/“false”(文本)从 PHP 返回到 javascript,
但我的 JAVASCRIPT IF 条件 似乎没有执行,即使条件是正确。

Javascript

var request = $.ajax({
type: "POST",
dataType: "text",
url: "",
data: { 
    'clientSecret': clientSecret,
    'oauthCode':oauthCode   
},
});

request.done(function(msg) {

    alert(msg);
    if(msg=="false"){       <----- DOES NOT EXECUTE
          //do stuff
    }



});

request.fail(function(jqXHR, textStatus) {
  alert( "Request failed: " + textStatus );
});

PHP

if(checkData($key,$oauthCode)==true){
        header("Content-Type: text/plain");
        echo "true"; 
        }
else{
        header("Content-Type: text/plain");
        echo "false";
        }

Javascript 成功警告“假”,

enter image description here

但是 if 条件永远不会被执行。 是不是返回数据类型有问题?
我在这里错过了什么?

最佳答案

只是一个建议,因为当您发现问题时,我已经开始为您的问题研究这个替代方案。

我不建议您使用 header 来执行此类任务。正如您所看到的,它们对预先输出很敏感。您可以使用 json 方法 (dataType: 'json') - 正如@charlietfl 善意建议的那样,或者使用 dataType = 'html'

使用 json 看起来像这样:

index.php

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Test</title>

        <!-- jQuery -->
        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>

        <script type="text/javascript">
            function startTestScript() {
                var clientSecret = $('#clientSecret').val();
                var oauthCode = $('#oauthCode').val();

                var ajax = $.ajax({
                    method: 'post',
                    dataType: 'json',
                    url: 'checkOauth.php',
                    data: {
                        'clientSecret': clientSecret,
                        'oauthCode': oauthCode
                    }
                });
                ajax.done(function (response, textStatus, jqXHR) {
                    if (response === true) {
                        alert('Response is ' + response + '. COOL!');
                    } else {
                        alert('Response is ' + response + '. UPS!');
                    }
                });
                ajax.fail(function (jqXHR, textStatus, errorThrown) {
                    alert('Request failed: ' + textStatus + '\n' + errorThrown);
                });
                ajax.always(function (response, textStatus, jqXHR) {
                    // alert('Finished executing this cool script.');
                });
            }
        </script>

        <style type="text/css">
            body {
                padding-top: 30px;
                text-align: center;
            }
            button {
                padding: 10px;
                background-color: #8daf15;
                color: #fff;
                border: none;
            }
        </style>
    </head>
    <body>

        <div>
            <label for="clientSecret">Client secret (int)</label>
            <input type="text" id="clientSecret" name="clientSecret" value="123">

            <br/><br/>

            <label for="oauthCode">OAuth code (int)</label>
            <input type="text" id="oauthCode" name="oauthCode" value="123">

            <br/><br/>

            <button type="button" name="testButton" onclick="startTestScript();">
                Start ajax
            </button>
        </div>

    </body>
</html>

checkOauth.php

<?php

/**
 * Check data.
 * 
 * @param mixed $value1
 * @param mixed $value2
 * @return TRUE if values are equal, FALSE otherwise.
 */
function checkData($value1, $value2) {
    return intval($value1) === intval($value2);
}

// Fetch posted values.
$clientSecret = isset($_POST['clientSecret']) ? $_POST['clientSecret'] : 0;
$oauthCode = isset($_POST['oauthCode']) ? $_POST['oauthCode'] : 0;

// Check data.
$dataIsValid = checkData($clientSecret, $oauthCode);

// Output the JSON-encoded result of checking data.
echo json_encode($dataIsValid);

关于javascript - AJAX 返回的字符串未验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47212514/

相关文章:

php - 变量中名称请求的数组不起作用

php - array_udiff_assoc() 和 array_diff_uassoc() 有什么区别?

javascript - jQuery 中的 AJAX 调用,什么定义了 "json"作为参数?

php - Bootstrap 表单使用 AJAX 和 PHP 添加新记录

javascript - 以编程方式(或可选地)覆盖 Chrome 的新标签页

javascript - 为什么变量没有定义?

javascript - 从 iframe 打开的弹出窗口重新加载 iframe

javascript - 指定哪个区域是日期排序

PHP/MYSQL 按 id 删除行

javascript - web2py控件表单,选择选项时显示字段