简体   繁体   中英

PlayFramework Result with Ajax

According to : PlayFramework Document 2.0 & PlayFramework Document 2.1

I know that in play I can return:

Ok()
badRequest()
created()
status()
forbidden()
internalServerError()
TODO

etc...

I would like to send with ajax an response with my information in it. Unfortunatelly play sends only status information, and some kind of object which I do not understand. Only method ok("Test message") sends status and my message information. Rest of it dosnt work. How to deal with it?

-- Edit --

I have ajax method:

$.post($("#assignmentsubmitAddress").text(), { 'units' : submittedUnits },
  function(response, status, xhr) {
showNotyfication(status, response);
  })

When I return ok("test"); In java script variable response I have just String test

When I return badRequest("test"); In java script variable response I have java object. When I print variable response I am getting Object object .

To send back a response in the json format to your client send a ok containing a string :

/**
 * Translate a json object into a json string.
 */
public static<T> String objToJson(Object obj)
{
    ObjectMapper mapper = new ObjectMapper();
    try{
        String json = mapper.writeValueAsString(obj);
        return json;
    }catch(java.io.IOException e){
        Logger.error(e.getMessage(), e);
    }
    return "";
}

public static Result actions()
{
    Object objToSendBack = ...
    return ok(objToJson(objToSendBack));
}

You can send back wathever you want, including html, but json is more convenient for communicating with javascript functions.

I've figure it out.

I've just changed variable response which is an object to response.responseText .

Now it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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