繁体   English   中英

使用ajax和grails更新SQL数据库

[英]updating SQL database using ajax and grails

我正在使用springsource工具套件中的grails,并且在更新SQL数据库时遇到了问题。 在页面中,要求用户输入其财产的详细信息,例如地址,城市等,并且一旦单击“保存”按钮,则需要将详细信息保存在数据库中。 现在,我需要做的是,每当用户单击“添加”按钮时,就将输入字段(地址,城市等)动态​​添加到页面中。 因此,因此,我需要使用AJAX将数据发布到服务器。 但是,我在更新它时遇到了麻烦。 这是view(.gsp文件)的代码-

<head>
<script type="text/javascript">
var rad1, rad2, button1, button2;
function add() {
var newP = document.createElement("p");
var input1, input2,
area = document.getElementsByTagName("form")[0];
input1 = document.createElement("input");
input1.type = "text";
input1.placeholder = "street";
input1.id = "address";
newP.appendChild(input1);
input2 = document.createElement("input");
input2.type = "text";
input2.placeholder = "city";
input2.id = "city"
newP.appendChild(input2);
    area.appendChild(newP);
    }
 </script>
 </head>
<body>
<form name='prop' method="post" action="save">
<g:hiddenField name="owners.id"  value="${session.user.id }" /> 
<input type="button"  value="+Add" onclick= "add();" ><br>
<input type="button" name="create" id="save_button" class="save" value="save" />
</form>
<script type="text/javascript" src="ajax.js"></script>
</body>

这是我的Ajax代码在单独的ajax.js文件中的样子-

$('#save_button').click(function()  {
var street = $('#address').val();
var city = $('#city').val();

$.ajax({
    type: "POST",
    url: "${createLink(controller: 'property', action: 'save')}",
    data: { address: street, city: city },
    success: function(data) {
        alert(data);
    }
});


});

这是我的属性控制器中的代码(保存操作)-

def save = {


    def propertyInstance = new Property(params)


    if (propertyInstance.save(flush: true)) {
        flash.message = "Property successfully added."
        redirect(controller:"user", action: "show", id:params.owners.id) 
    }
    else {
        render(view: "create", model: [propertyInstance: propertyInstance, id:params.owners.id])
    }
}

我在这里做错了什么? 我对Ajax一点都不熟悉,所以很抱歉,如果这是一个明显的错误,请帮助。

$('#address').val(); $('#city').val(); 将为您获取jQuery找到的第一个#address#city元素的值。 假设您要为所有地址和城市值创建一个数组,可以执行以下操作:

var cities = [];
var addresses = [];

$('#address​​​​').each(function() { 
    addresses.push($(this).val());
});​

$('#cities​​​​').each(function() { 
    cities.push($(this).val());
});​

如果页面上有两个地址和城市输入,结果将如下所示:

console.log(addresses); // [address1, address2]
console.log(cities); // [city1, city2]

编辑:要在提交时重置字段(如果更改jQuery选择器,则重置为“添加”),可以这样做:

$('#save_button').click(function() {
    // ... all your regular ajax stuff ...

    // reset the fields
    $('#address').val('');
    $('#city').val('');
    // ... and so on until you reset all fields
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM