在PHP上使用on-form元素制作ajax?

时间:2014-09-17 22:04:26

标签: jquery ajax

我有这种按钮

<button class="btn btn-danger" data-action="1">Delete record</button>

当有人点击该按钮,获取数据操作atributte并进行mysql查询时,我需要什么

$(function() {
    $("button).click(function(){
               $.ajax({
                   type: "POST",
            url: "process.php",
            data: 
                success: function(msg){
                    $(".alert-success").toggle();
                    $("#form-content").modal("hide");    
                },
            error: function(){
                $(".alert-error").toggle();
                }
                  });
    });
});

问题在于如何将data-action属性传递给process.php? 我知道我的数据:我可以传递表单元素,但是如何属性,以及后来在php中处理?

2 个答案:

答案 0 :(得分:0)

我会选择这种方法:

  1. 点击按钮
  2. 调用一个详细说明属性的函数,并生成一个有效的网址请求,其中包含您稍后需要处理的所有参数
  3. 调用ajax并传递刚刚生成的url。摆脱ajax中的“数据”。
  4. ajax请求将如下:

            $.ajax({
            type: "POST",
            url: "process.php?"+generateRequest()
            ...
    

    generateRequest()返回“action = 1”之类的内容。

    你的最终ajax网址将类似于process.php?action = 1

    这听起来怎么样?

答案 1 :(得分:0)

可以使用jQuery data-action函数或data("action")来获取attr("data-action")属性。

要将信息传递到您的服务器,您需要创建POST请求并将其发送到process.php?action=deleterecord之类的网址。删除行的操作是静态的,因此该部分会进入网址。要删除的行的信息将进入请求的数据部分。

<强>的Javascript

$(function() {
    $("button").click(function() {
        var action = $(this).data("action");
        var recordId = /* your record id */;
        $.ajax({
            type: "POST",
            url: "process.php?action=" + action,
            data: { recordid: recordId },
            success: function(msg){
                $(".alert-success").toggle();
                $("#form-content").modal("hide");    
            },
            error: function(){
                $(".alert-error").toggle();
            }
        });
    });
});

至于php脚本,你必须阅读$_GET$_POST超级变量。

switch ($_GET['action']) {
    case 'deleterecord':
        $recordId = parseInt($_POST['recordid']);
        // don't forget to validate your input
        // and then delete the record
        break;
}