【问题标题】:jQuery: Submitting a link with $.ajax POST with two variables?jQuery:提交带有两个变量的 $.ajax POST 链接?
【发布时间】:2011-08-24 16:53:52
【问题描述】:

我有以下三个变量:

var action,
    pubMode,
    token;

所有三个值都应通过 POST 和 ajax 提交。由于 POST 不接受网址,我完全不知道该怎么做?

function ajaxPost(action, pubMode, token) {

    $.ajax({
        url: ??,
        dataType: "text json",
        type: "POST",
        success: function(jsonObject,status) {

            console.log("function() ajaxPost : " + status);

        }
    });
}

你们能帮帮我吗!谢谢

【问题讨论】:

    标签: jquery ajax forms post


    【解决方案1】:

    $.ajax 有一个data 选项,您可以在其中将变量作为对象或查询字符串传递。

    POST 不像 GET 那样将变量附加到 URL 上。使用您要发布到的 URL 作为url 并使用data 发送变量。

    $.ajax({
        url: 'http://your/url/here',
        dataType: "text json",
        type: "POST",
        data: {action: action, pubMode: pubMode, token: token},
        success: function(jsonObject,status) {
    
            console.log("function() ajaxPost : " + status);
    
        }
    });
    

    【讨论】:

    • 谢谢。是否也可以使用以下变量名? my[pub_mode]: pubMode。每当我使用方括号时,代码就不再起作用了。
    • @mathiregister:您可以通过两种方式做到这一点。 1、使用查询字符串表示法:'my[pub_mode]='+pubMode+'&my[action]='+action+'&token='+token。 2、在对象中作为对象发送:{my: {pub_mode: pubMode, action:action}, token: token}
    【解决方案2】:

    使用data 参数向它传递一个对象:

    function ajaxPost(action, pubMode, token) {
    
        $.ajax({
            url: "targetpage.php",
            dataType: "text json",
            type: "POST",
            data: {action: action, pubMode: pubMode, token: token},
            success: function(jsonObject,status) {
    
                console.log("function() ajaxPost : " + status);
    
            }
        });
    }
    

    【讨论】:

    • 是否也可以在数据变量中使用方括号?就像我上面评论的那样? data: { my[pub_mode]: pubMode, token: token } 因为当我使用方括号时出现语法错误。
    • 没有。不确定您要在这里完成什么。那部分是 POST 变量的名称。
    【解决方案3】:
        url: "YOUR URL",
        data: {action: action, pubMode: pubMode, token: token}
    

    Documentation

    不要忘记您的 URL 可以包含 get 和 post 参数的组合。通过 URL 传递 get 。

    【讨论】:

      猜你喜欢
      • 2013-05-19
      • 2014-01-20
      • 2012-12-25
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2014-01-22
      • 2014-11-25
      • 1970-01-01
      相关资源
      最近更新 更多