直接从JS提交PHP表单(不含HTML)

时间:2017-07-31 14:55:59

标签: javascript php jquery ajax forms

我试图通过JS发送表单而不需要HTML,我有一个包含用户信息的表格,并且使用JS自动添加了按钮,我无法做到将该信息传递给HTML(JS表覆盖删除所有表单的HTML表格),有一种方法可以仅使用JS向PHP提交查询吗?

当我点击JS创建的按钮

时,这是运行的函数
function banAccount(id, username){
    swal({
        title: "Do you really want to ban "+username+"?",
        text: "Enter amount of days, -1 equals to permanent ban.",
        input: 'number',
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes",
        showLoaderOnConfirm: true,
        preConfirm: function (duration) {
          return new Promise(function (resolve, reject) {
            setTimeout(function() {
              if (duration === '0') {
                reject('Please type -1 for permanent ban or a number greater than 1!')
              } else {
                resolve()
              }
            }, 2000)
          })
        },
    allowOutsideClick: false
    }).then(function(duration){
        action_id = id;
        action_type = "ban";
        action_params = duration;
        alert("id:"+action_id+", type:"+action_type+", params:"+action_params)
        // Here's where I need to send "action_id", "action_type" and "action_params" to PHP
    });
}

2 个答案:

答案 0 :(得分:2)

您需要使用ajax。

$.ajax ({
    url: "PHP-PAGE-TO-POST-TO.php",
    data: { action_id : action_id, 
            action_type : action_type, 
            action_params : action_params },
    success: function( result ) {
        alert("Hi, testing");
        alert( result );
        //the variable "result" holds any value the PHP script outputs
    }
});

答案 1 :(得分:0)

如果警报(在swal的'then'部分(我猜测甜蜜警报))正在输出正确的数据,为什么不将数据发布到PHP文件?

$.post( "YOURFILE.php", { id: action_id, type: action_type, params: action_params } );