AJAX响应中的If语句


If statement in AJAX response

这是我在1.php页面上的代码。

$(document).ready(function(){
    $('#click').click(function(){
        var data;
        data = "action=post";
        $.ajax({
            type: "POST",
            url: "2.php",
            data: data,
            dataType: "json",
            success: function (data) {
                console.log(data);
                if (data['id'] === 1) {
                    alert('Hi methos get');
                    $('#show').text('methos get');
                }
                if (data['id'] === 2) {
                    alert('Hi methos post');
                    $('#show').text('methos post');
                }
            }
        });
    });
});

我的HTML代码是这样的。

<button id="click">Click On Me.</button>
<p id="show"></p>

概念很简单:当我点击按钮时,警报框将显示一些值,<p>将显示一些数值。

这是我的2.php页面代码:

if (isset($_POST['action'])) {
    if ($_POST['action'] == 'get') {
        $array = array("id" => '1', "config" => 'phppost',);
    }
    if ($_POST['action'] == 'post') {
        $array = array("id" => '2', "config" => 'phpget',);
    }
    Header('Content-Type: application/json');
    echo json_encode($array);
}

我现在只学习AJAX和jQuery,所以请帮助如何做到这一点。

亲爱的伙计们,两个数据['id']&data.id正在工作,问题是('1')我没有给值打引号,现在它正在工作,感谢所有人和@Nishan Senevirathna。我的最终代码是.

if (data['id'] === "1") {
     alert('Hi methos get');
     $('#show').text('methos get');
}
if (data['id'] === "2") {
    alert('Hi methos post');
    $('#show').text('methos post');
}

由于您使用JSON作为dataType,您将获得对象,因此在if中,您应该使用下面的

var obj = jQuery.parseJSON(data);
if (obj.id === 1) {
     // Your code goes here
} else if (obj.id === 2) {
     // Your code goes here
}

所以你的最终代码会变得像

$(document).ready(function(){
           $('#click').click(function(){
                    var data;
                    data = "action=post";
                    $.ajax({
                        type: "POST",
                        url: "2.php",
                        data: data,
                        dataType: "json",
                        success: function (data) {
                            console.log(data);
                            var obj = jQuery.parseJSON(data); 
                            if (obj.id === 1) {
                                alert('Hi methos get');
                                $('#show').text('methos get');
                            }
                            if (obj.id === 2) {
                                alert('Hi methos post');
                                $('#show').text('methos post');
                            }
                        }
                    });
                });
            });