使用ajax创建新的表行和表单提交

时间:2014-07-22 19:22:31

标签: javascript jquery ajax

我试图让这个ajax提交我的表单,但它只进入最后一次错误(意外错误!再试一次)。当我删除数据类型:json部分,然后警告未定义

    function ajax(action,id){
    if(action =="save")
        data = $("#userinfo").serialize()+"&action="+action;
    else if(action == "delete"){
        data = "action="+action+"&item_id="+id;
    }

    $.ajax({
        type: "POST", 
        url: "ajax.php", 
        data : data,
        dataType: "json",
        success: function(response){
            if(response.success == "1"){
                if(action == "save"){
                    $(".dert-form").fadeOut("fast",function(){
                    alert(here first);
                    }); 
                }else if(action == "delete"){
                    alert(here  to delete);
                }
            }
        },
        error: function(res){
            alert("Unexpected error! Try again.");
        }
    });
}

这里是ajax.php

if($action == "save"){
/* Check for blanks */ 
$err = "You have blank fields. ";
echo json_encode(
    array(
        "success" => "0",
        "msg"  => $err,                 
    )    
);

}

2 个答案:

答案 0 :(得分:1)

以下是您的代码的一个工作示例,并进行了一些调整:

function ajax(action,id){
    action = 'save';
    if(action =="save")
        data = $("#userinfo").serialize()+"&action="+action;
    else if(action == "delete"){
        data = "action="+action+"&item_id="+id;
    }

    $.ajax({
        type: "GET", 
        url: "http://demo.ckan.org/api/3/action/package_list", 
        data: data,
        dataType: "jsonp",
        success: function(response){
            console.log(response);
            if(response.success == "1"){
                if(action == "save"){
                    $(".dert-form").fadeOut("fast",function(){
                      alert("here first");
                    }); 
                }
                else if(action == "delete"){
                    alert("here  to delete");
                }
            }
        },
        error: function(res, textStatus, errorThrown){
            console.log("Unexpected error! Try again.");
        }
    });
}

我正在访问data.gov API端点并将响应记录到控制台。请注意,dataType必须为jsonp,因为我提出了跨域请求。您还可以查看JSBin I created with the above code

答案 1 :(得分:0)

使用json格式代替数据或查询字符串

 data = {"action":action,"item_id":id};