从javascript调用play 2.1控制器函数返回json数据对象

时间:2022-09-29 16:56:13

How to make play 2.1 controller function execute a captured external url and return json data object to javascript.

如何使play 2.1控制器函数执行捕获的外部url并将json数据对象返回给javascript。

  1. First of all InputStream is not opening an external url. errors out saying no protocol
  2. 首先,InputStream没有打开外部url。错误输出说没有协议
  3. play doesn't like JSONObject as return.
  4. play不喜欢JSONObject作为返回。

code underway -

代码开始-

Javascript

Javascript

$.ajax({
        url: "/documents/getjsontext/" + talksUrl ,
        type: 'GET',
        data: "",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(data){ do_this(data);},
        error: function () {alert("Error in Ajax Call");}
    });

Route- /documents/acontext/:jsonurl controllers.Class.acontext(jsonurl: String)

路线——/文件/ acontext /:jsonurl controllers.Class。acontext(jsonurl:字符串)

public static JSONObject acontext(String jsonurl) {

    InputStream is = new URL(jsonurl).openStream();

    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
}

1 个解决方案

#1


0  

first of all you need to add a JsRoutes class. i named it as "myJsRoutes"

首先,您需要添加一个jsroute类。我把它命名为“myjsroute”

public class CommonController extends Controller{

    public static Result javascriptRoutes() {
        response().setContentType("text/javascript");
        return ok(
            Routes.javascriptRouter("myJsRoutes",
                routes.javascript.Controller_name.function()
                    );
      }
}

now your js route is defined .and "myJsRoutes" can be further used to call in your scala file as :

现在定义了您的js路由,“myjsroute”可以进一步用于在scala文件中调用:

myJsRoutes.controllers.Controller_name.function_name().ajax({
 //your ajax handlers here
});

#1


0  

first of all you need to add a JsRoutes class. i named it as "myJsRoutes"

首先,您需要添加一个jsroute类。我把它命名为“myjsroute”

public class CommonController extends Controller{

    public static Result javascriptRoutes() {
        response().setContentType("text/javascript");
        return ok(
            Routes.javascriptRouter("myJsRoutes",
                routes.javascript.Controller_name.function()
                    );
      }
}

now your js route is defined .and "myJsRoutes" can be further used to call in your scala file as :

现在定义了您的js路由,“myjsroute”可以进一步用于在scala文件中调用:

myJsRoutes.controllers.Controller_name.function_name().ajax({
 //your ajax handlers here
});