Play 2.x:如何使用通用按钮发出AJAX请求

因此,我之前已经成功获得了Ajax请求,但是我一直必须使用一种表单,然后在提交末尾返回false,以便它不会刷新页面。


最近我也将JavaScript移到了一个单独的文件中,这导致我的@命令失败。因此,我是否不应该将我的网址设置为我的路线?


HTML:


<button id="saveAsDefaultButton">Save as default</button>

Playframework Java代码:


public static Result saveDefaultPhoneForUser(String handset) {

    User currentUser = User.findByName(session("name"));

    currentUser.lastControlledHandset = theHandset;

    currentUser.save();

    return ok();

}

路线:


POST    /                           controllers.Application.saveDefaultPhoneForUser(handset : String)

javascript:


$('#saveAsDefaultButton').click(function(evt) {

        $('#errors').hide();

        $.ajax({

            type : 'POST',

            url : "controllers.Application.saveDefaultPhoneForUser",

            data : $('#controlledPhone option:selected').text(),

            dataType : "text",

            success : function(data) {

                //setError('Call succedded');

                //$('#test1').attr("src", data)

            },

            error : function(data) {

                setError('Make call failed');

            }

        });

        return false;

    });

我肯定有办法做到这一点,我只是找不到运气。任何帮助大加赞赏。


jeck猫
浏览 485回答 3
3回答

UYOU

对于这项工作,您应该继续使用javascriptRoutes它,因为它会根据routes.conf生成正确的JS路径。您将在Zentask 示例中找到用法示例无论如何,现在您可以通过将更url改为来修复AJAX调用url : '@routes.Application.saveDefaultPhoneForUser()',这种方法要求将整个JS放在模板中,这是错误的。可以甚至应该将其移动到单独的JS文件中,并使其成为可能,您需要使用javascriptRoutes。更多...javascriptRoutes 尚未在官方文档中描述,但这里是逐步的介绍。尽管描述看起来很复杂,但实际上使用这种方式会带来很多好处。1.创建通用路线首先,您需要在conf/routes文件中创建通用路由:GET&nbsp; &nbsp; &nbsp;/item/:id&nbsp; &nbsp; &nbsp;controllers.Application.getItem(id: Long)POST&nbsp; &nbsp; /item/new&nbsp; &nbsp; &nbsp;controllers.Application.newItemPUT&nbsp; &nbsp; &nbsp;/item/:id&nbsp; &nbsp; &nbsp;controllers.Application.updateItem(id: Long)当然,您至少需要在Application控制器中创建以下三个动作:getItem(Long id){ ... }newItem() { ... }updateItem(Long id) { ... }2.创建一个将通用路由转换为JS的动作将其放置在某处,即。在您的Application控制器中叫它吧 javascriptRoutes()在该操作中,您将指向文件中的现有路由conf/routespublic static Result javascriptRoutes() {&nbsp; &nbsp; response().setContentType("text/javascript");&nbsp; &nbsp; return ok(&nbsp; &nbsp; &nbsp; &nbsp; Routes.javascriptRouter("myJsRoutes",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; routes.javascript.Application.getItem(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; routes.javascript.Application.newItem(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; routes.javascript.Application.updateItem(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //inside somepackage&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; controllers.somepackage.routes.javascript.Application.updateItem()&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; );}注意:请勿在方括号中设置任何参数。3.创建javascriptRoutes行动路线并将其包含在模板中路线 conf/routesGET&nbsp; &nbsp; &nbsp;/javascriptRoutes&nbsp; &nbsp; &nbsp;controllers.Application.javascriptRoutes<head>部分检视/views/main.scala.html<script type="text/javascript" src='@routes.Application.javascriptRoutes()'></script>4.在需要的地方使用javascriptRoutes从现在开始,您可以使用JS中的路由来获取正确的路径,而无需指定urland type。举个例子代替:&nbsp;$('.getAjaxForThisContainer').click(function(e) {&nbsp; &nbsp; var idToGet = $("#someField").val();&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; type : 'GET',&nbsp; &nbsp; &nbsp; &nbsp; url : '@routes.Application.getItem()',&nbsp; &nbsp; &nbsp; &nbsp; data : {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; id: idToGet&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; success : function(data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // ... some code on success&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; return false;});您可以使用简化版本(myJsRoutes从第2点开始):myJsRoutes.controllers.Application.getItem(idToGet).ajax({&nbsp; &nbsp; success : function(data) { ... some code ... }});要么myJsRoutes.controllers.Application.newItem().ajax({&nbsp; &nbsp; success : function(data) { ... some code ... }});等等...您无需指定type: "POST"-JS路由器将根据conf/routes规则使用正确的方法您可以使用纯JS中的语法id将记录(或其他参数)设置为GET或PUT(或其他方法)routes-like如果您的路线规则包含所有必需的参数,则可以将您的JS最小化:路线:GET&nbsp; &nbsp;/some/:a/:b/:c&nbsp; &nbsp; controllers.Application.getABC(a: String, b: Integer, c: String)JS:myJsRoutes.controllers.Application.getABC("a", 1, "b" ).ajax({});

一只萌萌小番薯

我喜欢“老好”的简单方法:1在页面中,使用JQuery,在一些偶数句柄中&nbsp;$.get('/giveme', {'arg': value}, function(data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; window.alert(data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;);2在服务器/播放端2.1路线: GET&nbsp; &nbsp; &nbsp; &nbsp; /giveme&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; controllers.Application.giveme(arg)2.2标量动作:object Application extends Controller {&nbsp;&nbsp; &nbsp; &nbsp; def giveme(arg:String) = Action {&nbsp; &nbsp; &nbsp; &nbsp; Ok(Json.toJson("hello," + arg ))&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java
JavaScript