相同的ajax调用必须传递不同的URL [英] DIfferent URL has to be passed for same ajax call

查看:72
本文介绍了相同的ajax调用必须传递不同的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行添加和编辑操作. 为了执行编辑操作,我使用以下链接作为参考 并完成它.如果单击编辑"按钮,则可以看到包含详细信息的弹出窗口.现在,我必须调用该函数,并且应该对添加和编辑都执行ajax调用.但是用于编辑的URL不同.该怎么办?

I am doing add and edit operation. To perform edit operation I have used the below link for reference and finished it. If I click the edit button I can see popup form with details. Now I have to call the funtion and should perform ajax call for both add and edit. But the URL for edit is different .How should I do it?Please refer my previous question

<html>

<head>
    <title>
        List of user
    </title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Add,Edit,Delete user</title>
    <link href="/static/css/qxf2_scheduler.css" rel="stylesheet">
    <link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet">
    <link href="//resources/demos/style.css" rel="stylesheet">
    <link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>


</head>

<body>
    <div id="dialog-confirm" title="Delete user?">
        <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>These user will be
            permanently deleted and cannot be recovered. Are you sure?</p>
    </div>
    <div class="container col-md-offset-1">
        <h2 class="grey_text text-center">user List</h2>

        <input class="btn btn-info" type="button" id="create-user" value="Add user">


        <div class="row-fluid top-space-20">
            {% if result | length == 0 %}
            <div>
                <p>There are no user details ,If you want you can add it </p>
            </div>
            {% else %}
            <table class="table table-striped">
                <thead>
                    <th>user name</th>
                    <th>user duration</th>
                    <th>user Description</th>
                    <th>user requirements</th>
                    <th>Actions</th>
                </thead>
                {% for each_item in result %}
                <tbody>
                    <td>{{each_item.user_name}}</td>
                    <td>{{each_item.user_time}}</td>
                    <td>{{each_item.user_description}}</td>
                    <td>{{each_item.user_requirement}}</td>
                    <td>
                            <input class="edituser btn btn-info" type="button" value="Edit" data-user-id = "{{each_item.user_id}}" data-user-name="{{each_item.user_name}}" data-user-description="{{each_item.user_description}}" data-user-requirement="{{each_item.user_requirement}}" data-user-duration="{{each_item.user_time}}">
                        <input type="button" class="btn btn-info" onclick="delete_user(this)" value="Delete"
                            id="delete-button{{each_item.user_id}}" data-delete-user-id="{{each_item.user_id}}"
                            data-delete-department-id="{{department_id}}" />
                    </td>
                </tbody>
                {% endfor %}
                {% endif %}
            </table>
        </div>
    </div>
    <div id="dialog-form" title="Create new user">
        <p class="validateTips">All form fields are required.</p>

        <form>
            <fieldset>
                <label for="username">user name</label>
                <input type="text" name="username" id="username" class="text ui-widget-content ui-corner-all">
                <label for="duration">Duration</label>
                <input type="text" name="duration" id="duration" class="text ui-widget-content ui-corner-all">
                <label for="description">Description</label>
                <input type="text" name="description" id="description" class="text ui-widget-content ui-corner-all">
                <label for="requirements">Requirements</label>
                <input type="requirements" name="requirements" id="requirements"
                    class="text ui-widget-content ui-corner-all">
                <input type="hidden" id='departmentId' ,value="{{department_id}}">
                <input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
            </fieldset>
        </form>
    </div>

    <script>
        $(function () {
            var dialog, form,
                username = $("#username"),
                duration = $("#duration"),
                description = $("#description"),
                requirements = $("#requirements"),
                allFields = $([]).add(username).add(duration).add(description).add(requirements),
                tips = $(".validateTips");

            function updateTips(t) {
                console.log(t);
                tips
                    .text(t)
                    .addClass("ui-state-highlight");
                setTimeout(function () {
                    tips.removeClass("ui-state-highlight", 1500);
                }, 500);
            }

            function checkLength(o, n, min, max) {

                if (o.val().length > max || o.val().length < min) {
                    o.addClass("ui-state-error");
                    updateTips("Length of " + n + " must be between " +
                        min + " and " + max + ".");

                    return false;
                } else {
                    return true;
                }
            }

            function addUser(url,msg) {
                var valid = true;                
                allFields.removeClass("ui-state-error");
                var username = $("#username");
                var duration = $("#duration");
                var description = $("#description");
                var requirements = $("#requirements");
                var departmentId = document.getElementById("departmentId").value;
                valid = valid && checkLength(username, "username", 3, 16);
                valid = valid && checkLength(duration, "duration", 3, 16);
                valid = valid && checkLength(description, "description", 3, 300);
                valid = valid && checkLength(requirements, "requirments", 5, 300);
                console.log(url,msg);
                if (valid) {
                    var username = $("#username").val();
                    var duration = $("#duration").val();
                    var description = $("#description").val();
                    var requirements = $("#requirements").val();
                    var departmentId = document.getElementById("departmentId").value;
                    $("#users tbody").append("<tr>" +
                        "<td>" + username + "</td>" +
                        "<td>" + duration + "</td>" +
                        "<td>" + description + "</td>" +
                        "<td>" + requirements + "</td>" +
                        "</tr>");
                    $.ajax({
                        type: 'POST',
                        url: url,
                        data: {
                            'username': username,
                            'duration': duration,
                            'description': description,
                            'requirements': requirements
                        },
                        success: function (result) {
                            console.log(result);                            
                            alert(msg);
                            document.location.href = "/departments";
                        },
                    })

                    dialog.dialog("close");
                }
                return valid;
            }

            dialog = $("#dialog-form").dialog({
                autoOpen: false,
                height: 400,
                width: 350,
                modal: true,
                buttons: {
                    "Create user": addUser,
                    Cancel: function () {
                        dialog.dialog("close");
                    }
                },
                close: function () {
                    form[0].reset();
                    allFields.removeClass("ui-state-error");
                }
            });

            form = dialog.find("form").on("submit", function (event) {
                event.preventDefault();
                var url = '/department/%d/user'%departmentId;
                var msg = 'The user has been added'
                addUser(url,msg);


            });
            editDialog = $("#dialog-form").dialog({
                autoOpen: false,
                height: 400,
                width: 350,
                modal: true,
                buttons: {
                    "Edit user": addUser,
                    Cancel: function () {
                        dialog.dialog("close");
                    }
                },
                close: function () {
                    form[0].reset();
                    allFields.removeClass("ui-state-error");
                }
            });

            form = dialog.find("form").on("submit", function (event) {
                event.preventDefault();
                var url = '/department/%d/user/edit'%departmentId;
                var msg = 'The user has been edited'
                addUser(url,msg);


            });


            $("#create-user").button().on("click", function () {
                console.log("I am first");
                dialog.dialog("open");
            });
            $(".edituser").button().on("click", function () {
                var id = $(this).attr("data-user-id");
                var userName=$(this).attr("data-user-name");
                var userDuration=$(this).attr("data-user-duration");
                var userDescription=$(this).attr("data-user-description");
                var userRequirements=$(this).attr("data-user-requirement");
                console.log(id,userName);
                $("#username").val(userName);
                $("#duration").val(userDuration);
                $("#description").val(userDescription);
                $("#requirements").val(userRequirements);

                editDialog.dialog("open");
            });
        });
    </script>

    <script>
        //Confirmation message for deleteing user
        var user_id;
        var department_id;
        var dialog = $("#dialog-confirm").dialog({
            resizable: false,
            height: "auto",
            autoOpen: false,
            width: 400,
            modal: true,
            buttons: {
                "Delete": function () {
                    console.log("user_id" + user_id)
                    $.ajax({
                        type: 'GET',
                        url: '/user/' + user_id + '/departments/' + department_id + '/delete',
                        data: { 'user_id': user_id },
                        success: function (data) {
                            window.location.reload();
                            console.log("successfully deleted the data")
                        }
                    })
                    $(this).dialog("close");
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });
        function delete_user(action_delete) {
            user_id = action_delete.getAttribute("data-delete-user-id");
            department_id = action_delete.getAttribute("data-delete-department-id");
            dialog.dialog("open");
        }
    </script>




</body>


</html>

推荐答案

通过为Ajax创建通用功能:

By Making the common function for the Ajax:

function doAjaxCall(var url,var data,var method,var callBackFunction)
{
    $.ajax({
      type: method,
      url: url,
      data: data,
      success: function(data){
         callBackFunction(data);
      }
    });
}

像这样调用函数

function onAdd(data){
// Code to append
}
doAjaxCall("/add",userData,"POST",onAdd);

function onEdit(data){
// Code to update
}
doAjaxCall("/update",userData,"PUT",onEdit);

这篇关于相同的ajax调用必须传递不同的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆