Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
794 views
in Technique[技术] by (71.8m points)

php - Send a boolean value in jQuery ajax data

I'm sending some data in an Ajax call. One of the values is a boolean set to FALSE. It is always evaluated as TRUE in the PHP script called by the Ajax. Any ideas?

$.ajax({
    type: "POST",
    data: {photo_id: photo_id, 
           vote: 1, 
           undo_vote: false},   // This is the important boolean!
    url: "../../build/ajaxes/vote.php",
    success: function(data){
        console.log(data);
    }
}); 

In vote.php, the script that is called in the above Ajax, I check the boolean value:

if ($_POST['undo_vote'] == true) {
    Photo::undo_vote($_POST['photo_id']);
} else {
    Photo::vote($_POST['photo_id'], $_POST['vote']);
}

But the $_POST['undo_vote'] == true condition is ALWAYS met.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A post is just text, and text will evaluate as true in php. A quick fix would be to send a zero instead of false. You could also put quotes around your true in PHP.

if ($_POST['undo_vote'] == "true") {
    Photo::undo_vote($_POST['photo_id']);
} else {
    Photo::vote($_POST['photo_id'], $_POST['vote']);
}

Then you can pass in true/false text. If that's what you prefer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...