如何在这个ajax帖子中添加更多变量......?

时间:2014-04-14 21:11:55

标签: jquery ajax

我正在制作游戏,我需要通过帖子请求将一些变量发送到排行榜页面。

这是我目前的邮政编码:

var toDatabase = confirm('Do you want to save your score to the database?');
if (toDatabase) {
    $.post("leaderboards.php", {"Level1": "Level1"}, function() {
    window.location.href="leaderboards.php";
});
} else {
    $.post("gameL2.php", {"Level1": "Level1"}, function() {
      window.location.href='gameL2.php';
    });
}

这个链接到leaderboards.php文件的顶级代码也是我希望添加更多变量的代码。如何才能做到这一点?我是否添加了一对新的花括号?

4 个答案:

答案 0 :(得分:4)

通过对象发送数据,只需添加另一个键/ val:

$.post("leaderboards.php", {"Level1": "Level1", "anotherKey": "anotherVal"}, function() {

答案 1 :(得分:1)

您只需向数据对象添加更多变量。

if (toDatabase) {
    $.post("leaderboards.php", {"Level1": "Level1","variable1":0,"variable2":"value","variable3":546}, function() {
    window.location.href="leaderboards.php";
});

等等。

答案 2 :(得分:1)

第二个参数只是一个对象:

$.post("leaderboards.php", {"Level1": "Level1", "abc": "def", "num": 123}, function() {

只需用逗号分隔

答案 3 :(得分:0)

如果你有一个你希望发送的基础对象,并且它只会在发生的两个不同事件中添加两个,那么你可以使用jQuery.extend

var baseObj = {
   Level1: "Level1"
}

if (toDatabase) {
    $.extend(baseObj, { complete: true });
}else{
    $.extend(baseObj, {doSomething: "yeah" });
}

这就是为了进一步添加另一个键/值对而更加灵活