Home > Software design >  htmx and django: return HX-Trigger header with json data show error `SyntaxError: JSON.parse...`
htmx and django: return HX-Trigger header with json data show error `SyntaxError: JSON.parse...`

Time:04-26

I'm following the examples in https://htmx.org/headers/hx-trigger/

my view

def my_view(request):
    res = render(request, 'index.html')
    res.headers["HX-Trigger"] = ...
    return res

this code works

res.headers["HX-Trigger"] = "showMessage"

while below code will cause error SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data

res.headers["HX-Trigger"] = {"showMessage": "Here Is A Message"}

What should I do?

CodePudding user response:

You need to pass a valid JSON string as the header - not a dictionary, because a dictionary will not be converted to JSON automatically (which is why the client fails to parse it).

The following will work:

res.headers["HX-Trigger"] = '{"showMessage": "Here Is A Message"}'   # Note, this is a string

or, if you don't want to generate the JSON string manually:

import json

res.headers["HX-Trigger"] = json.dumps({"showMessage": "Here Is A Message"})
  • Related