Back

Technologies:

javascriptjavascript
jqueryjquery
avatar
Tolerim
13 days ago

What is the process for reading byte strings produced by Marshall on the jQuery side?

To create a response on the Django server side, the following code is used:
def index(request):
    if request.method == 'POST':
        ...
        url = reverse(settlementcreate, args=[settlementid])
        return HttpResponse(marshal.dumps({'url': url}), content_type="application/json")

When the URL is passed to jQuery, it's not being decoded correctly, causing unexpected characters to appear. Here is the code for the jQuery AJAX call that is being used:
$.ajax({
      type : 'POST',
      url :  url,
      data : {'text': city_info},
      success : function(response){
          $("#city-href").attr('href', response['url']); 
      },
      error : function(response){
          console.log(response)
      }
});

This issue can be resolved by switching to a regular JSON library instead of using marshal on the server side. Do you have any thoughts on this?
Answers(2)
avatar
Vogi
13 days ago
Verified Answer
It seems that the issue is caused by the use of the marshal library on the server side. The marshal library is used to serialize Python objects into a byte stream and then deserialize them back into Python objects. However, it is not designed to be used for encoding JSON data. Instead, you should use the built-in json library to encode your data into JSON format before sending it to the client. Here's an example of how you can use the json library to encode your data:
def index(request):
    if request.method == 'POST':
        ...
        url = reverse(settlement_create, args=[settlement_id])
        return HttpResponse(json.dumps({'url': url}), content_type="application/json")
This should resolve the issue with unexpected characters appearing in your jQuery AJAX call. Let me know if you have any other questions!

Sources

Creating a JSON response using Django and PythonHTML not getting decoded properly by Middleware in Django 2.2 #691 - GithubHow to read byte strings generated by marshall on the jquery side?Execute code in Django after response has been sent to the clientWhy does django return 301 and 302 as server response codes after a ...
avatar
Tolerim
13 days ago
It seems like the issue is with the way the JSON response is encoded with the marshal library on the server side. Instead of using marshal.dumps(), you can use the built-in json.dumps() method to encode the JSON response. This should ensure that jQuery can decode the response correctly. Here is an example of how you can modify the code:
import json

def index(request):
    if request.method == 'POST':
        ...
        url = reverse(settlement_create, args=[settlement_id])
        return HttpResponse(json.dumps({'url': url}), content_type="application/json")
By using the json library instead of marshal, the response should be properly encoded and decoded by jQuery.
;