Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Returning JSON directly #13

Open
macfire opened this issue Feb 15, 2016 · 0 comments
Open

Returning JSON directly #13

macfire opened this issue Feb 15, 2016 · 0 comments

Comments

@macfire
Copy link

macfire commented Feb 15, 2016

A solution for returning JSON to where Sijax.request() is called in javascript:

Python setup:

# Extend BaseResponse
class SijaxJson(sijax.response.BaseResponse):
    def json(self, data):
        #return data
        params = {"json": data}
        return self._add_command("json", params)

# Usage
class MySijaxHandlers(object):
    @staticmethod
    def get_json(obj_response, obj):
        try:
            db_result = MyTable.objects.get(id=obj['id'])  # example using MongoEngine
            result_json = db_result.to_dict()  # jsonify object
            obj_response.json(result_json)  # return using new method
        except Exception as e:
            obj_response.html('#feedback',  "%s" % e)


# Target extend class in your post method
g.sijax.register_object(MySijaxHandlers, response_class=SijaxJson)

Javascript:

// the key was in understanding that the "success" method could be over-ridden
Sijax.request('get_json', [args], {
              data: {csrf_token: "token_here"},
              success: function(response) {
                    console.log( response[0].json );
              }
});

jQuery.ajax could be used directly, of course, but by extending the Sijax BaseResponse server side, it is easy and convenient to simply target my existing custom Sijax handlers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant